国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

nodejs redis 發布訂閱機制封裝實現方法及實例代碼

2019-11-19 18:27:47
字體:
來源:轉載
供稿:網友

 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.VeVB.COm/201612/yuanma/WebApiCore-master(VeVB.COm).rar

1 采用DDD模式開發,充血模型 2 添加Dapper擴展,默認實現增刪改查基本操作。利用AutoMapper 做實體轉換,減少重復勞動。 3 依賴注入融合Autofac,倉儲層和應用層自動注入 4 實現JWT驗證 5 加入swagger 文檔 6 單元測試添加了xunit,MyMvc 可以方便對webapi測試 7 數據庫版本控制

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 崇阳县| 友谊县| 巴东县| 鞍山市| 将乐县| 久治县| 遂溪县| 塔城市| 封丘县| 新昌县| 新安县| 平原县| 庆元县| 隆昌县| 沂南县| 呼伦贝尔市| 贡觉县| 垦利县| 贡山| 章丘市| 阿勒泰市| 崇阳县| 团风县| 司法| 同江市| 五莲县| 肇庆市| 四川省| 波密县| 临沧市| 永寿县| 镇平县| 庆元县| 西贡区| 资阳市| 孟州市| 什邡市| 故城县| 襄樊市| 海南省| 和平区|