当前位置: 首页 > 后端技术 > PHP

Laravel5.4,广播事件,pusher配置及使用

时间:2023-03-29 14:04:13 PHP

发表于2年前,文章重新整理迁移。原地址是https://learnku.com/articles/。。。最近想写个聊天室,所以才明白看了一下laravel的eventbroadcast,参考来自http://laravelacademy.org/pos...但是在关注博主的时候,发现事件触发成功,但是在pusher调试控制台上没有接收到事件。调试后发现问题。首先,我们来创建一个事件:phpartisanmake:eventTestEvent最后,事件的代码如下,这里有一点要注意,如果事件不继承则使用IlluminateContractsBroadcastingShouldBroadcast;接口,然后触发事件不会将事件发送到推送服务器。use...//如果事件不继承则useIlluminate\Contracts\Broadcasting\ShouldBroadcast;接口,然后触发事件不会将事件发送到推送服务器。类TestEvent实现ShouldBroadcast{使用Dispatchable、InteractsWithSockets、SerializesModels;//类型需要是publicpublic$msg;公共函数__construct($msg){$this->msg=$msg;}publicfunctionbroadcastOn(){return['test'];}}为了测试方便,我们创建一个artisan命令触发event.phpartisanmake:commandTestEventCommand打开命令类app/Console/Commands/TestEventCommand.php编辑如下classTestEventCommandextendsCommand{protected$signature='pusher:测试{消息}';protected$description='推杆测试';公共函数__construct(){parent::__construct();}publicfunctionhandle(){event(new\App\Events\TestEvent($this->argument('消息')));}}打开app/Console/Kernel.php,将新建的命令类添加到$commandsprotected$commands=[Commands\TestEventCommand::class,];事件代码基本完成,然后importpushercomposerrequirepusher/pusher-php-server当pusher导入成功后,需要在env中配置BROADCAST_DRIVER,需要配置为pusherconfig/broadcasting.php文件BROADCAST_DRIVER默认为null-PUSHER_APP_ID=you_app_id-PUSHER_APP_KEY=you_app_key-PUSHER_APP_SECRET=you_app_secret-BROADCAST_DRIVER=pusher另外,这里测试发现如果QUEUE_DRIVER配置为redis,触发事件时不会调用IlluminateBroadcastingBroadcastManager下的createPusherDriver方法。即不会产生pusher类发送事件。QUEUE_DRIVER应该配置成sync配置之后,我们就可以通过artisan命令向pusher服务器发送事件,phpartisanpusher:test"hello",然后在pusherdebug-console上就可以看到了