nodejs redis 發布訂閱機制封裝
最近項目使用redis,對publish 和 subscribe的使用進行了瞭解,並進行了封裝。
var config = require('../config/config');var log = require("./loghelp");var redis = require("redis");function initialclient(param) { var option={ host: config.redis.host, port: config.redis.port}; if(param) { option=Object.assign(option,param); } redis.print let client = redis.createClient(option); client.on("error", function(err) { log.error(err); }); return client;}
/*example:* let channel="ryan"; redis.pubSub.registerHandlers("ryan",msg=> console.log(msg)); redis.pubSub.subscribe(channel); redis.pubSub.publish(channel,"hello from chen");*/class PubSub{ constructor(){ this.sub=initialclient(); this.handlers=new Map(); this.subAction=(channle,message)=>{ let actions= this.handlers.get(channle)||new Set(); for(let action of actions) { action(message); } } this.alredyPublishs=[]; this.subConnected=false; } publish(channel,message) { let action=()=>{ let pub=initialclient(); pub.publish(channel,message); }; if(this.subConnected===false) { this.alredyPublishs.push(action); } else action(); } registerHandlers(channel,action) { var actions=this.handlers.get(channel)||new Set(); actions.add(action); this.handlers.set(channel,actions); } subscribe(channel) { let self=this; this.sub.subscribe(channel,function (err,reply) { if(err) log.error(err); self.subConnected=true; for(let publish of self.alredyPublishs) publish(); console.log(reply); }); this.sub.on("message", function (channel, message) { self.subAction(channel,message); }); } tearDown() { this.sub.quit(); }}
然後通過exports.pubsub=new PubSub() 將其暴漏,可保證是單例。在程式啟動時,調用
registerHandlers 註冊特定通道的處理邏輯,然後調用
subscribe 訂閱通道。
在合適時機調用publish,這個機制可以實現分布式下所有用戶端watch 同一個資料的更改。
本人全手工打造的dotnetcore webapi 架構,可實現快速開發。
地址:http://xiazai.jb51.net/201612/yuanma/WebApiCore-master(jb51.net).rar。
1 採用DDD模式開發,充血模型 2 添加Dapper擴充,預設實現增刪改查基本操作。利用AutoMapper 做實體轉換,減少重複勞動。 3 依賴注入融合Autofac,倉儲層和應用程式層自動注入 4 實現JWT驗證 5 加入swagger 文檔 6 單元測試添加了xunit,MyMvc 可以方便對webapi測試 7 資料庫版本控制
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!