问题描述
我们很少有 node.js 进程应该能够传递消息,最有效的方法是什么?如何使用 node_redis pub/sub
We have few node.js processes that should be able to pass messages,What's the most efficient way doing that?How about using node_redis pub/sub
进程可能在不同的机器上运行
the processes might run on different machines
推荐答案
如果你想从一台机器向另一台机器发送消息并且不关心回调,那么 Redis 发布/订阅是最好的解决方案.实现起来真的很容易,Redis 也很快.
If you want to send messages from one machine to another and do not care about callbacks then Redis pub/sub is the best solution. It's really easy to implement and Redis is really fast.
首先,您必须在其中一台机器上安装 Redis.
First you have to install Redis on one of your machines.
连接到Redis真的很容易:
Its really easy to connect to Redis:
var client = require('redis').createClient(redis_port, redis_host);
但不要忘记在防火墙中打开 Redis 端口!
But do not forget about opening Redis port in your firewall!
然后你必须为每台机器订阅某个频道:
Then you have to subscribe each machine to some channel:
client.on('ready', function() {
return client.subscribe('your_namespace:machine_name');
});
client.on('message', function(channel, json_message) {
var message;
message = JSON.parse(message);
// do whatever you vant with the message
});
你可以跳过your_namespace
而使用全局命名空间,但你迟早会后悔的.
You may skip your_namespace
and use global namespace, but you will regret it sooner or later.
发送消息也很容易:
var send_message = function(machine_name, message) {
return client.publish("your_namespace:" + machine_name, JSON.stringify(message));
};
如果你想发送不同类型的消息,你可以使用 pmessages 代替消息:
If you want to send different kinds of messages, you can use pmessages instead of messages:
client.on('ready', function() {
return client.psubscribe('your_namespace:machine_name:*');
});
client.on('pmessage', function(pattern, channel, json_message) {
// pattern === 'your_namespace:machine_name:*'
// channel === 'your_namespace:machine_name:'+message_type
var message = JSON.parse(message);
var message_type = channel.split(':')[2];
// do whatever you want with the message and message_type
});
send_message = function(machine_name, message_type, message) {
return client.publish([
'your_namespace',
machine_name,
message_type
].join(':'), JSON.stringify(message));
};
最佳做法是按功能命名您的进程(或机器)(例如 'send_email'
).在这种情况下,如果进程(或机器)实现了多个功能,它可能会订阅多个频道.
The best practice is to name your processes (or machines) by their functionality (e.g. 'send_email'
). In that case process (or machine) may be subscribed to more than one channel if it implements more than one functionality.
实际上,可以使用 redis 构建双向通信.但它更棘手,因为它需要为每条消息添加唯一的回调通道名称,以便在不丢失上下文的情况下接收回调.
Actually, it's possible to build a bi-directional communication using redis. But it's more tricky since it would require to add unique callback channel name to each message in order to receive callback without losing context.
所以,我的结论是:如果您需要发送和忘记"通信,请使用 Redis,如果您需要成熟的双向通信,请研究其他解决方案.
这篇关于什么是最有效的 node.js 进程间通信库/方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!