Socket.io & Redis pub / sub architecture broadcast function

I would appreciate it if someone could help me with a little doubt.

What is the difference between using the socket.io broadcast function and designing the architecture from pub / sub to Redis ?.

For example, in the following example, the node.js server listens for (socket.io) CRUD requests (creates) for the "key" (model "todo") and the value "data". At that moment when he receives it, he again returns to one user and is broadcast to all users listening to the same "channel".

socket.on('todo:create', function (data, callback) { var id = guid.gen() , todo = db.set('/todo/' + id, data) , json = todo._attributes; socket.emit('todos:create', json); socket.broadcast.emit('todos:create', json); callback(null, json); }); 

But there is another way to "broadcast" something using socket.io, and uses the pub / sub platform with Redis for key: value functions. For example, in the following case, we listen to a CRUD request based on the “key” (model), function (creation), and value (data). But in this case, after receiving it, it is not sent through "socket.broadcast.emit ()", but is published in Redis:

 socket.on(key + ':create', function (data, callback) { var t = new ModelClass(data) , name = '/' + key + ':create'; t.save(function (err) { pub.publish(key, JSON.stringify({key: name, data: t})); }); }); 

Thus, on the server side, every change made on the model (and published to Redis) will be intercepted (handler) and sent to the client side of the user (in my case, backbone.js), which will display its model in accordance with the key: received value:

 sio.on('connection', function (socket) { sub.on('message', function (channel, message) { var msg = JSON.parse(message); if (msg && msg.key) { socket.emit(msg.key, msg.data); } }); 

So my question is very simple :-): What is the difference between both architectures? which one is more scalable? better design? mode?

It seems to me that the pub / sub architecture is suitable for platforms that, of course, do not support "realtime", like Ruby, unlike node.js, which supports it natively. . I am wrong?

+6
source share
2 answers

The Socket.io broadcast method will be broadcast to all sockets connected to the current Node.js server, but what if your application becomes popular and you need more than one server to host all socket.io connections? Using Redis' Pub / Sub, your messages can be distributed to many servers at once.

0
source

You might want to take a look at RedisStore at Socket.io. Instead of using MemoryStore, you can set socket.io to use RedisStore. so that you can increase your application.

http://www.ranu.com.ar/2011/11/redisstore-and-rooms-with-socketio.html

As mentioned here ( fooobar.com/questions/88805 / ... ), using Socket.io with RedisStore can lead to some problems with sessions, because sessions are not shared between workers.

0
source

Source: https://habr.com/ru/post/917359/


All Articles