环境:
前端:antd pro + laravel-echo-client
后端:laravel 5.7,laravel-echo-service
大概流程:
前端:主页创建client,开始请求数据 (频道 user_id)。如有数据就发送一个通知。
聊天室页创建client,进入后请求数据 (频道 order_id)。如有数据就在聊天页显示内容。
后端:laravel-echo-service 配置好conifg,启动
laravel 创建触发器-监视器,
laravel 配置 channels
启动队列(redis),
event() 触发事件。
流程:event->redis存入队列->laravel-echo-service接收并发送给客户端.
需求文档:
错误排查方法:
1.event 触发事件后 redis 中会有队列生成,keys * 能够查看是否有队列。
2.laravel-echo-service 文档中有测试接口,可以判断是否因为laravel是否因为laravle原因导致不通。
3.laravel-echo-service 有测试模式,cmd能够看到客户端是否连接和是否发送消息。
4.启动队列的命令为 php artisan queue:work 能够看到是否触发了任务。
实际代码:
前端:
import Echo from "laravel-echo"; #引入laravel-echo包
window.io = require('socket.io-client');
window.Echo = new Echo({ #创建echo 实例
broadcaster: 'socket.io',
host: window.location.hostname + ':16001' #修改的监听端口,默认6001
});
window.Echo.private('otc_orderNotice.'+getId()) #监听的频道名
.listen('.server.orderNotice', (e) => { #触发器别名
//逻辑
});
后端:
//触发器类class OrderNotice implements ShouldBroadcast{/*** 状态更新信息.** @var string*/public $user_id ;public $date ;public $message;public function __construct( $user_id , $message = "" ){$this-> user_id = $user_id ;$this->message = $message;
$this-> date = Carbon::now()->toDateTimeString();}/*** {@inheritDoc}* @see \Illuminate\Contracts\Broadcasting\ShouldBroadcast::broadcastOn()*/public function broadcastOn(){//频道名称return new PrivateChannel ( 'otc_orderNotice.' .$this-> user_id );}/*** 别名* @return string*/public function broadcastAs(){return 'server.orderNotice' ;}}
//触发器和监视器配置
class EventServiceProvider extends ServiceProvider{/*** The event listener mappings for the application.** @var array*/protected $listen = ['App\Events\Event' => ['App\Listeners\EventListener' ,],'App\Events\OrderNotice' => ['App\Listeners\OrderNotification'],];/*** Register any events for your application.** @return void*/public function boot(){parent ::boot();}}
//路由的两种配置方法use App\Broadcasting\OrderChannel;Broadcast ::channel( 'otc_orderStatus.{orderId}' , OrderChannel:: class );Broadcast ::channel( 'otc_orderNotice.{userId}' , function ($user,$user_id){return true ;});
//触发事件
event(new OrderNotice(1, "这是消息"));