NodeJS操作Redis发布订阅消息

首先先说一下流程:

1.保存数据到Redis,然后将member值publish到 chat频道(publish.js功能)

2.readRedis.js文件此前一直在监听chat频道,readRedis.js文件接收到member后,用它作为条件去Redis中去查找,拿到score数据

代码如下:

publish.js文件:

var redis = require("redis");  
var client = redis.createClient(6379, "127.0.0.1");

function zadd(key, score, member) {  
    client.zadd(key, score, member, function () {
        client.publish("chat", member);//client将member发布到chat这个频道
        //然后订阅这个频道的订阅者就会收到消息
    });
}
for (var i = 0; i < 10; i++) {  
    zadd("z", i, "" + i);//发布10次
    console.log("第" + i + "次");
}

readRedis.js文件:

var redis = require("redis");  
var client = redis.createClient(6379, "127.0.0.1");  
var client1 = redis.createClient(6379, "127.0.0.1");

function getRedisData() {  
    //客户端连接redis成功后执行回调
    client.on("ready", function () {
        //订阅消息
        client.subscribe("chat");
        client.subscribe("chat1");
        console.log("订阅成功。。。");
    });

    client.on("error", function (error) {
        console.log("Redis Error " + error);
    });

    //监听订阅成功事件
    client.on("subscribe", function (channel, count) {
        console.log("client subscribed to " + channel + "," + count + "total subscriptions");
    });

    //收到消息后执行回调,message是redis发布的消息
    client.on("message", function (channel, message) {
        console.log("我接收到信息了" + message);
        dealWithMsg(message);
    });

    //监听取消订阅事件
    client.on("unsubscribe", function (channel, count) {
        console.log("client unsubscribed from" + channel + ", " + count + " total subscriptions")
    });
}

function dealWithMsg(message) {  
    //按照message查询内容
    client1.zscore("z", message, function (err, reply) {
        console.log(message + "的内容是:" + reply);
    });
}
getRedisData();  

--EOF--