首页 > 代码库 > nodejs redis的发布与订阅

nodejs redis的发布与订阅

  redis的发布(pub)是把消息推送到不同的频道或指定的频道,订阅(sub)是订阅一个或多个频道接收来自频道的消息,取消订阅(unsubscribe)。

概念性的就不多做介绍,看源码:

/* 
* redis发布订阅
 */
"use strict";

let configFile = require(‘../../include/commons‘).CONFIG_FILE;
let config = require(‘../../resources/config/‘ + configFile);

let RedisModel = require(‘./../redis.model‘);
let RedisSubClient = require(‘./redisSubClient‘);
let RedisPubClient = require(‘./redisPubClient‘);
let redisPubConn = RedisPubClient.redisClient().connection;
let redisSubConn = RedisSubClient.redisClient().connection;

class PubSub{
    constructor(){
        this.sub=redisSubConn;
        this.handlers=new Map();
        this.subAction=(channle,message)=>{
            console.log("接收消息:"+message);
       message = JSON.parse(message);
       //消息处理。。。
      }
        this.alredyPublishs=[];
        this.subConnected=false;
    }

    publish(channel,message)
    {
        let action=()=>{
            let pub=redisPubConn;
            pub.publish(channel,message);
            console.log("发布消息:channel:"+channel+",message:"+message);
        };
        if(this.subConnected===false)
        {
            this.alredyPublishs.push(action);
        }
        else{
            action();
        }
    }

    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); }); } } // Expose class module.exports = new PubSub();

  注意事项:

  1、只要客户端订阅了频道, 发布订阅的指令其他均不能操作,否则会报错。我在实现时发现用了订阅的客户端也不能用来发布消息,会报错。

  2、客户端可简单定义一个方法 var redisClient = redis.createClient(6379,"ip");

参考博客:http://www.cnblogs.com/ryansecreat/p/6121834.html

nodejs redis的发布与订阅