nodejs redis 發布訂閱機制封裝實現方法及執行個體代碼_node.js

來源:互聯網
上載者:User

 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 資料庫版本控制

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.