如何让 Node.js 进程相互通信
我有一个nodejs聊天应用程序,其中多个客户端使用socketio连接到一个公共聊天室。我想将其扩展到多个节点进程,可能在不同的机器上。但是,连接到同一房间的客户端将无法保证命中同一节点进程。例如,用户 1 将访问节点进程 A,用户 2 将访问节点进程 B。他们位于同一个房间,因此如果用户 1 发送消息,用户 2 应该会收到该消息。由于它们的连接由不同的进程管理,因此实现此目的的最佳方法是什么?
我考虑过让节点进程连接到 redis。这至少解决了进程 A 会知道房间里还有另一个用户(用户 2),但它仍然无法发送给用户 2 的问题,因为进程 B 控制着它联系。有没有办法为redis注册“值更改”回调?
我处于无法控制任何路由或负载平衡的服务器环境中。
I have an nodejs chat app where multiple clients connect to a common chat room using socketio. I want to scale this to multiple node processes, possibly on different machines. However, clients that connect to the same room will not be guaranteed to hit the same node process. For example user 1 will hit node process A and user 2 will hit node process B. They are in the same room so if user 1 sends a message, user 2 should get it. What's the best way to make this happen since their connections are managed by different processes?
I thought about just having the node processes connect to redis. This at least solves the problem that process A will know there's another user, user 2, in the room but it still can't send to user 2 because process B controls that connection. Is there a way to register a "value changed" callback for redis?
I'm in a server environment where I can't control any of the routing or load balancing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个node.js进程都可以通过redis pub/sub 订阅某个频道并监听您传递的消息到这个频道。例如,当用户 1 连接到第一台机器上的进程 A 时,您可以在 Redis 中存储有关该用户的信息以及哪台机器上的哪个进程管理该用户的信息。然后,当连接到第二台机器上的进程 B 的用户 2 向用户 1 发送消息时,您可以将其发布到该通道,并检查哪台机器上的哪个进程负责管理与用户 1 的通信,并做出相应的响应。
Both node.js processes can be subscribed to some channel through redis pub/sub and listen to messages which you pass to this channel. For example, when user 1 connects to process A on the first machine, you can store in redis information about this user along with the information which process on which machine manages it. Then when user 2, which is connected to process B on the second machine, sends a message to user 1, you can publish it to this channel and check which process on which machine is responsible for managing communication with user 1 and respond accordingly.
我对此做了一些研究。下面是我的发现:
就像 yojimbo87 所说,你首先只使用 redis pub/sub(非常优化)。
http://comments.gmane.org/gmane.comp.lang.javascript .nodejs/22348
蒂姆卡斯韦尔写道:
但是当序列化/反序列化成为你的瓶颈时,我会尝试使用 https://github.com/pgriess/节点消息包。我也想测试一下,因为我认为越早越好?
I have done(did) some research on this. Below my findings:
Like yojimbo87 said you first just use redis pub/sub(is very optimized).
http://comments.gmane.org/gmane.comp.lang.javascript.nodejs/22348
Tim Caswell wrote:
But when serialization / deserialization becomes your bottle-neck I would try to use https://github.com/pgriess/node-msgpack. I would also like to test this out, because I think the sooner you have this the better?