node.js - laravel 5.2 自动触发广播事件

标签 node.js laravel redis socket.io

我正在使用 BROADCAST_DRIVER=redis 来触发 laravel 5.2 事件。 一旦我在命令提示符下运行以下服务:

  1. 在第一个选项卡中,运行 node socket.js

    您应该看到“监听端口 3000”

  2. 在第二个选项卡中运行 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/

相关文章:

node.js - 如何在NextJS Vercel项目中进行301重定向?

mongodb - Redis/Mongo 排序列表的复杂度

ruby-on-rails - 在 Ruby 和 Redis 中匹配现场玩家的最佳策略?

php - Laravel Guzzle GET请求

node.js - 在 Node.js 机器人服务中实现 Redis

javascript - NodeJS v15.7.0 | Electron v11.2.3 | Uncaught Error : Uncaught TypeError: Class constructor <Class> cannot be invoked without 'new' , 但是什么?

node.js - VS Code 不缩进 4 个空格,但仅针对单个文件

json - 您可以从部署在 GitHub 上的 heroku 应用程序写入 JSON 文件吗

jquery - Summernote js编辑器Serialize()获取HTML代码?

用于从 https 排除 POST 端点的 Laravel .htaccess 配置