使用Redis和Socket.io在Laravel 5.2中进行事件广播

时间:2016-04-13 20:37:06

标签: node.js websocket redis socket.io laravel-5.2

我将Laravel 5.1更新为5.2,该事件不再播出。

我正在使用带有php 7和hhvm,Node 5.3.0,Redis 3.0.6的Laravel家园。

Redis工作正常。 (我尝试过Redis :: publish)。

我解雇了这个事件,但我没有收到任何消息。

活动类

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class UserSignedUp extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $username;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($username)
    {print_r($username);
        $this->username = $username;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return ['test-channel'];
    }
}

路线

Route::get('event', function () {
    $data = [
        'event' => 'UserSignedUp',
        'data' => [
            'username' => 'JohnDoe'
        ]
    ];

// Works fine
    Redis::publish('test-channel', json_encode($data));

// It does not broadcast anything
    event(new \App\Events\UserSignedUp('JohnDoe'));
});

Socket.io服务器

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();

redis.subscribe('test-channel', function (err, count) {
});

redis.on('message', function (channel, message) {
    console.log('Message Recieved: ' + message);

    message = JSON.parse(message);

    io.emit(channel + ':' + message.event, message.data);
});

http.listen(3000, function () {
    console.log('Listening on Port 3000');
});

Env config

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis
BROADCAST_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

1 个答案:

答案 0 :(得分:5)

每个被触发的事件都被推送到redis队列中,要广播你必须在队列中释放作业,你可以使用

php artisan queue:listen ....

php artisan queue:work

命令