我有以下代码:
/routes/web.php
<?php
use App\Events\UserSignedUp;
Route::get('/', function () {
$data = [
'event' => 'UserSignedUp',
'data' => [
'username' => 'JohnDoe'
]
];
//Redis::publish('test-channel', json_encode($data));
event(new UserSignedUp('JohnDoe'));
return view('welcome');
});
我正在使用的功能:event(...)
。
我还有以下Event
文件:
/app/Events/UserSignedUp.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class UserSignedUp implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $username;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($username)
{
$this->$username = $username;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('test-channel');
}
}
然后,我正在Node.js
文件上监听事件:
/socket.js
var server = require('http').Server();
var io = require('socket.io')(server);
var Redis = require('ioredis');
var port = process.env.PORT || 3000;
var redis = new Redis();
redis.subscribe('test-channel');
redis.on('message', function(channel, message) {
console.log(channel, message);
});
server.listen(port, function(){
console.log('listening on *:' + port);
});
我的问题是,在上面的文件中: /routes/web.php ,我使用:
event(new UserSignedUp('JohnDoe'));
事件未到达Node.js
侦听器。但是,该事件已正确到达Redis
,因为我可以使用$ redis-cli monitor
命令看到它。
[编辑1] 以下是调用event(...)
函数时得到的内容:
1541489387.307573 [0 127.0.0.1:52109] "SELECT" "0"
1541489387.308379 [0 127.0.0.1:52109] "RPUSH" "queues:default" "{\"displayName\":\"App\\\\Events\\\\UserSignedUp\",\"job\":\"Illuminate\\\\Queue\\\\CallQueuedHandler@call\",\"maxTries\":null,\"timeout\":null,\"timeoutAt\":null,\"data\":{\"commandName\":\"Illuminate\\\\Broadcasting\\\\BroadcastEvent\",\"command\":\"O:38:\\\"Illuminate\\\\Broadcasting\\\\BroadcastEvent\\\":7:{s:5:\\\"event\\\";O:23:\\\"App\\\\Events\\\\UserSignedUp\\\":2:{s:8:\\\"username\\\";N;s:6:\\\"socket\\\";N;}s:10:\\\"connection\\\";N;s:5:\\\"queue\\\";N;s:15:\\\"chainConnection\\\";N;s:10:\\\"chainQueue\\\";N;s:5:\\\"delay\\\";N;s:7:\\\"chained\\\";a:0:{}}\"},\"id\":\"7CjGqwcRXoZhVIJyFU8AcQ5aTW8G6Cke\",\"attempts\":0}"
另一方面,当我使用时:
Redis::publish('test-channel', json_encode($data));
事件正确到达Node.js
侦听器。
[编辑2] 以下是调用Redis::publish(...)
函数时得到的内容:
1541489590.930114 [0 127.0.0.1:52124] "SELECT" "0"
1541489590.930872 [0 127.0.0.1:52124] "PUBLISH" "test-channel" "{\"event\":\"UserSignedUp\",\"data\":{\"username\":\"JohnDoe\"}}"
关于为什么事件没有到达Node.js
侦听器事件的任何想法是什么?
谢谢。