UNPKG

mm_os

Version:

MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。

161 lines (142 loc) 3.49 kB
const { Drive } = require('mm_machine'); /** * 广播器 * 进行websocket、socket、mqtt广播 */ class Pusher extends Drive { static config = { // 广播器名称 name: 'default', // 推送配置 // 推送类型: websocket, mqtt、socket type: 'websocket', // 推送策略: realtime(实时), batch(批量) strategy: 'realtime', // 批量推送间隔(毫秒) batch_interval: 100, // 推送队列大小 queue_size: 1000, // 最大重试次数 max_retry: 3, // 重试间隔(毫秒) retry_interval: 500, // 是否启用压缩 compression: false }; /** * 构造函数 * @param {object} config 配置参数 * @param {object} parent 父对象 */ constructor(config, parent) { super({ ...Pusher.config, ...config || {} }, parent); // 推送队列 this._push_queue = []; // 推送计时器 this._batch_timer = null; } } /** * 获取模板目录 * @returns {string} 模板目录 */ Pusher.prototype.getTplDir = function () { return __dirname; }; /** * 初始化核心 * @param {object} adapter 适配器 * @param {object} eventer 事件总线 * @param {object} logger 日志管理器 */ Pusher.prototype._initCore = async function (adapter, eventer, logger) { // 初始化依赖项 if (logger) { this.setLogger(logger); } if (eventer) { this.getEventer = function () { return eventer; }; } if (adapter) { this.getAdapter = function () { return adapter[this.config.type]; }; } // 初始化批量推送计时器 if (this.config.strategy === 'batch') { this._startBatchTimer(); } // 注册事件监听 this._registerEvents(); }; /** * 注册事件监听 * @private */ Pusher.prototype._registerEvents = function () { // 监听实体数据变化事件 let eventer = this.getEventer(); eventer.on('entity_changed', (data) => { console.log('entity_changed', data); }); // 监听实体创建事件 eventer.on('entity_created', (data) => { console.log('entity_created', data); }); // 监听实体删除事件 eventer.on('entity_deleted', (data) => { console.log('entity_deleted', data); }); }; /** * 广播消息给所有连接的客户端 * @param {string} method 方法名 * @param {object} params 参数 */ Pusher.prototype.broadcast = function (method, params) { }; /** * 启动 */ Pusher.prototype._start = async function () { this.log('info', '启动'); // 启动批量推送计时器 if (this.config.strategy === 'batch') { this._startBatchTimer(); } }; /** * 停止 */ Pusher.prototype._stop = async function () { // 停止批量推送计时器 if (this._batch_timer) { clearInterval(this._batch_timer); this._batch_timer = null; } // 清空推送队列 this._push_queue = []; this.log('info', 'stopped'); }; /** * 销毁 */ Pusher.prototype._destroy = function () { try { // 停止批量推送计时器 if (this._batch_timer) { clearInterval(this._batch_timer); this._batch_timer = null; } // 清空存储引用 this._push_queue = []; this.log('info', 'destroyed'); // 移除所有监听器 this.removeAllListeners(); } catch (error) { this.log('error', `销毁失败`, error); } }; exports.Pusher = Pusher;