利用Redis发布/订阅特性来广播消息,nodejs订阅Redis的消息,订阅到消息后利用前端创建的websocket来发送通知前端更新消息
这就类似于用收音机广播的时候,你想下次继续收听,你首先得订阅这个频道,后面想听只要打开收音机,调到对应的频道,就可以了。
一、后端Redis广播消息
定义广播事件代码相关片段
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class NotificationBroadcast extends Event implements ShouldBroadcast
{
public $connection = 'broadcast'; //连接名称
public $broadcastQueue = '{notification_broadcast}'; //广播队列名称
public $tries = 1;
public $data; //数据
public $channel; //频道
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($data, $channel)
{
$this->data = $data;
$this->channel = $channel;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel($this->channel);
}
}
使用广播事件代码相关片段
event(new NotificationBroadcast($data, $channel));
二、nodejs订阅Redis消息前端获取Redis频道, 发送到node socket, 在node socket 接口中去订阅Redis, 订阅成功后等待 Redis 的 message 事件, 当Redis 发送广播后, message 事件被触发。
const Koa = require('koa')
const router = require('koa-router')()
const redis = require('redis')
const websockify = require('koa-websocket')
const ROOT_PATH = '../../'
const app = websockify(new Koa())
const Config = require(`${
ROOT_PATH}config`)
const prefix = '/ksocket/'
const redisConfig = {
host: '118.178.11.233',
port: '3025',
password: 'xsjkd855',
db: 9
}
const routes = [
{
path: `${
prefix}getMessage`, // /ksocket/getMessage
cb: async ctx => {
console.log('this is socket broadcast')
const {
broadcast } = ctx