本文主要实现使用node.js连接redis数据库,pub/sub。当有数据压入到list中时,pub消息,然后在sub端从list中取出相应的数据
pub.js
var redis = require("redis");
var client = redis.createClient();
client.lpush('usr','test:value'); //将数据压入到list usr中
client.lpush('like','test1:value1');
client.lpush('dislike','test2:value2');
client.publish("usr", 'new');
client.publish("like", 'test');
client.publish("dislike", 'test2');
sub.js
var redis = require("redis");
var fs = require("fs");
var client1 = redis.createClient();
var client2 = redis.createClient();
var len = 0;
client1.on("message", function (channel, message) {
getValue(channel);
/*
console.log(channel + ": " + message);
fs.appendFile("./log.txt",message+'\n',function(e){ //将数据追加到日志文件中
if(e) throw e;
});
*/
});
//var myDate = new Date(); //获取当前时间
//console.log(myDate);
client1.subscribe("usr");
client1.subscribe("like");
client1.subscribe("dislike");
function getValue(channel)
{
client2.llen(channel,function(err,reply){ //回调函数形式获取结果,可以使用redis.print来查看结果
//console.log(reply);
var client = redis.createClient();
for(var i=0;i<reply;i++)
{
client.rpop(channel,function(err,reply){
console.log(reply);
});
}
});
}