import { core, GFCfg } from "cgserver" import { RedisManager } from "cgserver" import { GLog } from "cgserver" import _, { uniqueId } from "underscore" import { EErrorCode } from "../Config/_error_" export let GPSRedisTool:PSRedisTool=null class PSRedisTool { protected _publishRedisMgr:RedisManager=null protected _subscribeMgr:RedisManager=null async init() { this._publishRedisMgr = new RedisManager() this._subscribeMgr= new RedisManager() await this._publishRedisMgr.init(GFCfg.db.redis) await this._subscribeMgr.init(GFCfg.db.redis) } onMessage(cb:Function) { this._subscribeMgr.on("message",cb) } publish(channel:string,msg:string) { this._publishRedisMgr.publish(channel,msg) } subscribe(channel:string) { this._subscribeMgr.subscribe(channel) } } GPSRedisTool = new PSRedisTool() export class BaseSubRedis { protected _sub_channel="hall" protected _pub_channel="texas" protected _id_cbs:Array=[] //是否把消息输出到文件日志 protected _msg2file=false async init() { await GPSRedisTool.init() GPSRedisTool.subscribe(this._sub_channel) GPSRedisTool.onMessage(this.onMessage.bind(this)) } async onMessage(channel:string,msg:string) { let jsonData = JSON.parse(msg) if(jsonData._id&&this._id_cbs[jsonData._id]) { this._id_cbs[jsonData._id](jsonData) this._id_cbs[jsonData._id]=undefined delete this._id_cbs[jsonData._id] return } let cmd:string = jsonData.cmd if(!cmd) { GLog.error(" subredis no cmd:"+msg) return } cmd = cmd.toLowerCase() if(this["on"+cmd]) { let res = await this["on"+cmd](jsonData)||{} res.cmd=cmd res._id=jsonData._id this.publish(res) } else { //GLog.error(" no do with subredis cmd:"+msg) return } } protected _getNewMsg(cmd:string,_id?:string) { let msg:any= { _id:_id||_.uniqueId(), cmd:cmd } return msg } async publish(msg:any,channel?:string) { if(!core.isObject(msg)) { GLog.error("redis pub msg must be an object") return } if(!msg.cmd||!core.isString(msg.cmd)) { GLog.error("redis pub msg must have cmd(string)") return } return new Promise((resolve,reject)=> { GLog.info("sub send------------") //GLog.info(msg,msg.cmd!="round") GLog.info(msg,this._msg2file) msg._id=_.uniqueId() this._id_cbs[msg._id]=(jsonData)=> { resolve(jsonData) } let handler = setTimeout(()=> { let error = {errcode:EErrorCode.Handle_Failed} if(this._id_cbs[msg._id]) { this._id_cbs[msg._id](error) this._id_cbs[msg._id]=undefined delete this._id_cbs[msg._id] } resolve(error) },3000) let _msg = JSON.stringify(msg) GPSRedisTool.publish(channel??this._pub_channel,_msg) }) } }