oak-backend-base/lib/cluster/DataSubscriber.js

80 lines
3.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const env_1 = require("./env");
const console_1 = require("console");
/**
* 集群行为备忘:
* 当socket.io通过adapter在集群间通信时测试行为如下测试环境为pm2 + cluster-adapter其它adpater启用时需要再测一次
* 1当client连接到node1并join room1时只有node1上会有create room事件room结构本身在结点间并不共享
* 2当某一个node执行 .adapter.to('room1').emit()时连接到任一结点的client均能收到消息但使用room可以实现跨结点推包
* 3) serverSideEmit执行时如果有callback而不是所有的接收者都执行callback的话会抛出一个异常意味着不需要本结点来判定是否收到全部的返回值了
*/
class DataSubscriber {
ns;
nsServer;
constructor(ns, nsServer) {
this.ns = ns;
this.nsServer = nsServer;
this.startup();
}
/**
* 来自外部的socket连接监听数据变化
*/
startup() {
this.ns.on('connection', async (socket) => {
try {
const { instanceId } = (0, env_1.getClusterInfo)();
// console.log('on connection', instanceId);
socket.on('sub', async (events) => {
events.forEach((event) => socket.join(event));
});
socket.on('unsub', (events) => {
// console.log('instance:', process.env.NODE_APP_INSTANCE, 'on unsub', JSON.stringify(ids));
events.forEach((id) => {
socket.leave(id);
});
});
}
catch (err) {
socket.emit('error', err.toString());
}
});
if (this.nsServer) {
this.nsServer.on('connection', async (socket) => {
try {
const { instanceId } = (0, env_1.getClusterInfo)();
console.log('on nsServer connection', instanceId);
socket.on('sub', async (events) => {
console.log('on nsServer sub', instanceId, events);
events.forEach((event) => socket.join(event));
});
socket.on('unsub', (events) => {
// console.log('instance:', process.env.NODE_APP_INSTANCE, 'on unsub', JSON.stringify(ids));
events.forEach((id) => {
socket.leave(id);
});
});
}
catch (err) {
socket.emit('error', err.toString());
}
});
}
}
publishEvent(event, records, sid) {
const { instanceId } = (0, env_1.getClusterInfo)();
// console.log('publishEvent', instanceId);
if (sid) {
this.ns.to(event).except(sid).emit('data', records, event);
}
else {
this.ns.to(event).emit('data', records, event);
}
}
publishServerEvent(identifier, event, ...rest) {
(0, console_1.assert)(this.nsServer);
this.nsServer.to(identifier).emit(event, ...rest);
}
}
exports.default = DataSubscriber;