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();
当publish的内容为对象的时候,要把对象转化成Buffer类型,例如:
function publishRegisterResult(responseBody) { responseBody = { name: "lw", age: 30 }; var bufferBody = new Buffer(JSON.stringify(responseBody), 'utf8'); redis.ac_register_redis.publish(config.redis_prefix.special_register_result, bufferBody, function (err, result) { if (err) { console.log("publish register result error: ", err.toString()); } else { console.log("publish register result success"); } }); }
注意, 只要客户端订阅了频道, 除了SUBCRIBE,UNSUBCRIBE,PSUBCRIBE,PSUBCRIBE,就不能执行其他命令。
参考:http://wiki.jikexueyuan.com/project/redis/subscribe-to-release-mechanism.html