如何解决将redis订阅消息中继到websocket
使用模式(*:*:*)
订阅redis,该模式每分钟接收一次数据;还可以作为Websocket服务器运行,以检查特定的订阅消息,并且如果该特定订阅消息的数据是redis返回的,则将redis返回的数据直接推送到该WS通道
例如:如果WS客户端想要订阅一个名为Binance:BTC-USDT:1m的通道,并且该数据每分钟都来自redis,那么我如何在获取新数据后立即将其发送到WS客户端来自Redis的数据?
最有效的方法是什么?
export {};
const redis = require("redis");
const WebSocket = require("ws");
const subscriber = redis.createClient();
subscriber.psubscribe("*:*:*");
const wss = new WebSocket.Server({ port: 8080 });
subscriber.on("pmessage",function (pattern,channel,message) {
console.log(message);
});
wss.on("connection",function connection(ws) {
ws.on("message",function incoming(message) {
console.log("Server Received: %s",message);
});
ws.send("something from server");
});
解决方法
ws.ts
import { IWSClient } from "./types/IChannel";
export default class WSHandler {
sockets: Object = {};
bindChannelWS(channel: any,client: IWSClient) {
if (this.sockets[channel] === undefined) {
this.sockets[channel] = [client];
} else {
this.sockets[channel].push(client);
}
}
publishToChannel(channel: string,message: string) {
if (this.sockets[channel] !== undefined) {
this.sockets[channel].forEach(function (client: IWSClient) {
console.log(JSON.parse(message));
client.send(message);
});
}
}
}
index.ts
export {};
const redis = require("redis");
const WebSocket = require("ws");
import { IWSClient } from "./types/IChannel";
import WSHandler from "./ws";
const subscriber = redis.createClient();
subscriber.psubscribe("*:*:*");
const wss = new WebSocket.Server({ port: 8080 });
var wsHandler = new WSHandler();
subscriber.on("pmessage",function (
pattern: any,channel: string,message: string
) {
wsHandler.publishToChannel(channel,message);
});
wss.on("connection",function connection(ws: IWSClient) {
ws.on("message",function incoming(_subMessages: string) {
let subMessages: Array<string> = JSON.parse(_subMessages);
console.log("Server Received: ",subMessages);
subMessages.forEach((channel) => wsHandler.bindChannelWS(channel,ws));
});
ws.send(JSON.stringify({ connection: "Initiated" }));
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。