node.js+redis消息队列

因为新的项目中使用了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!


参考:

http://blog.sina.com.cn/s/blog_62b832910100xok2.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值