因为新的项目中使用了redis的消息队列功能去处理一些比较耗时或者耗资源的事情,所以了解了一下redis的消息队列机制。
在redis中这被成为发布(pub)与订阅(sub)。


基本流程:
发送者(发送信息的客户端)不是将信息直接发送给特定的接收者(接收信息的客户端),而是将信息发送给频道(channel),然后由频道将信息转发给所有对这个频道感兴趣的订阅者。

但是因为是轻量级实现,所以没有持久化。


例子:

publisher.js

var redis = require("redis");
 
try{ 
    var client = redis.createClient(6379, "10.0.192.27");
 
    client.on(
        "error",
        function(err){
            console.log("err"+err);
            }
 
    );
    client.on('ready',
        function(){
            client.publish('testFirst',"hi! first!");
            client.publish('testSecond',"hi! second!");
            client.end();
        }
    );
}
catch(e){
        console.log("err:"+e);
}


subscriber.js

var sys = require("sys");
try{ 
	var client = require("redis").createClient(6379, "10.0.192.27");
	
	sys.puts("waiting for messages...");
	client.on(
	    "error",
	    function(err){
	        console.log("err"+err);
	        }
	);
	client.subscribe("testSecond");
	client.on('subscribe',
	    function(channel,count){
	        console.log("channel:" + channel + ", count:"+count);
	        }
	);
	client.on('message',
	    function(channel,message){
	        console.log("channel:" + channel + ", msg:"+message);
	        }
	);
	client.on('unsubscribe',
	    function(channel,count){
	        console.log("channel:" + channel + ", count:"+count);
	        }
	);
} catch(e){
        console.log("err:"+e);
}




这样启动subscrib端,会出现下面的信息

waiting for messages...
 channel:testSecond, count:1


然后启动publisher端,则subscrib端会接受到testSecond频道发过来的消息了。

waiting for messages...
 channel:testSecond, count:1
 from: testSecond / message: hi! second!
 channel:testSecond, msg:hi! second!