Redis Pub-Sub 或 Socket.IO 的广播 [英] Redis Pub-Sub or Socket.IO's broadcast
问题描述
我看到了这个片段:
io.sockets.on('connection', function(socket) {
const subscribe = redis.createClient();
const publish = redis.createClient();
socket.on('publish', function(channel, data) {
publish.publish(channel, data);
});
socket.on('psubscribe', function(channel) {
subscribe.psubscribe(channel);
});
subscribe.on("pmessage", function(pattern, channel, message) {
socket.emit('message', { channel: channel, data: message });
});
});
在客户端
$(".action").click(function() {
socket.emit('publish', 'game.#{gameid}.action.' + $(this).data('action'),
JSON.stringify({ nick: "#{nick}", ts: Date.now() })
);
我想知道为什么?Socket.IO 没有自己的广播机制吗?为什么选择 Redis 的 Pub-Sub 而不是 Socket.IO?难道我们不能这样做:
And I'm wondering why? Doesn't Socket.IO have its own broadcast mechanism? Why choose Redis' Pub-Sub over Socket.IO? Can't we just do like this:
io.sockets.on('connection', function(socket) {
socket.on('action', function(channel, data) {
socket.broadcast.to(channel).emit(data)
});
});
如果有理由使用 Redis,会有什么好处?坚持?
And if there is a reason to use Redis, what would be the benefit? Persistence?
推荐答案
我选择在我的实时活动流项目中使用 Redis Pub Sub 和 Socket.io 的原因 (http://blog.cloudfoundry.com/2012/06/05/node-activity-streams-app-2/) 是因为我想拥有多个 Web 服务器(Cloud Foundry 上的实例或 Heroku 上的 dynos).据我所知,Socket.io 将消息存储在(一个网络服务器的)内存中,那么它如何可能广播到连接到另一个网络服务器的客户端?
The reason I chose to use Redis Pub Sub with Socket.io in my Real Time Activity Stream project (http://blog.cloudfoundry.com/2012/06/05/node-activity-streams-app-2/) was because I wanted to have multiple web servers (instances on Cloud Foundry or dynos on Heroku). As far as I could see, Socket.io stores the messages in memory (of one webserver), so how it could possibly broadcast to clients which are connected to another webserver?
查看帖子和如果有帮助,请告诉我
Check out the post and let me know if it helps
这篇关于Redis Pub-Sub 或 Socket.IO 的广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!