2017-10-19 83 views
0

我在我的流明应用程序中有一个名为'Event1'的事件和一个事件监听器'Event1Listener'。当事件1被触发时,我需要将自定义消息发布到名为'channel1'的redis频道。我怎样才能做到这一点?如何使用流明广播将消息发布到redis频道?

Event1.php

<?php 
    namespace App\Events; 
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast; 
    class Event1 extends Event implements ShouldBroadcast 
    { 
     /** 
     * Create a new event instance. 
     * @return void 
     */ 
     public function __construct() {   
     } 
     /** 
     * Get the channels the event should be broadcast on. 
     * 
     * @return array 
     */ 
     public function broadcastOn() { 
      return ['channel1']; 
     } 
    } 
?> 

Event1Listener.php

<?php 

    namespace App\Listeners; 

    use App\Events\Event1; 
    use Illuminate\Queue\InteractsWithQueue; 
    use Illuminate\Contracts\Queue\ShouldQueue; 

    class Event1Listener { 
     /** 
     * Create the event listener. 
     * 
     * @return void 
     */ 
     public function __construct(){ 
     } 
     /** 
     * Handle the event. 
     * 
     * @param Event1 $event 
     * @return void 
     */ 
     public function handle(Event1 $event) { 
      echo "What should I add here?"; 
     } 
    } 
?> 

回答

0

假设你已经配置Redis如果查不出来的laravel documentationlumen documentation

要发布消息的引导你ld使用命令

public function handle(Event1 $event) { 
    Redis::publish('channel1', json_encode(['foo' => 'bar'])); 
} 
+0

当Redis :: publish()被调用时出现错误。在我的composer.json中我有''照亮/ redis“:”〜5.1“'和''predis/predis”:“〜1.0”',并且在侦听器文件中也调用了'Use Redis'。供应商文件夹包含illuminate/redis目录,并在我的bootstrap/app.php文件中注册了Illuminate \ Redis \ RedisServiceProvider。 – LJP

+0

请分享你的'app.php'文件,并试过'composer dump-autoload'? – linktoahref

+0

'$ app-> configure('broadcasting'); $ app-> register(App \ Providers \ EventServiceProvider :: class); $ app-> register(Illuminate \ Redis \ RedisServiceProvider :: class);' – LJP