我正在使用 BROADCAST_DRIVER=redis 来触发 laravel 5.2 事件。 一旦我在命令提示符下运行以下服务:
在第一个选项卡中,运行 node socket.js
您应该看到“监听端口 3000”
在第二个选项卡中运行 redis-server --port 3001
在它并排打开两个浏览器窗口后,在第一个窗口中点击 URL:“http://your-project-name.app/fire”
第二个:“http://your-project-name.app/test”
继续刷新第一个窗口,您应该会看到第二个页面的内容已更新。
但我不想刷新页面,我只想在后台触发广播事件,也不想运行服务“node socket.js and redis-server --port 3004”。
我已经安装了 node、redis、express ioredis 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(3004, function(){
console.log('Listening on Port 3004');
});
最佳答案
您需要使用 Redis Pub/Sub
These Redis commands allow you to listen for messages on a given "channel". You may publish messages to the channel from another application, or even using another programming language, allowing easy communication between applications / processes.
首先,让我们使用订阅方法通过 Redis 在 channel 上设置一个监听器。我们将把这个方法调用放在一个 Artisan 命令中,因为调用 subscribe 方法开始了一个长时间运行的过程:
<?php
namespace App\Console\Commands;
use Redis;
use Illuminate\Console\Command;
class RedisSubscribe extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'redis:subscribe';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Subscribe to a Redis channel';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Redis::subscribe(['test-channel'], function($message) {
echo $message;
});
}
}
转到终端,在您的根文件夹中启动命令
php artisan redis:subscribe
现在,我们可以使用 publish 方法向 channel 发布消息:
Redis::publish('test-channel', json_encode(['foo' => 'bar']));
此方法不使用nodejs。
关于node.js - laravel 5.2 自动触发广播事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37611563/