I am new to redis pub / sub. I have a chat on a system that is similar to IM. Therefore, I would like to use redis pub / sub. Since I reviewed the samples, most of them are chat-based. On my system, I will have several chats between users, for example:
A:B A:C D:C E:F
So the lines above are the rooms. And I implemented a server with node.js as shown below;
var store = redis.createClient(); var pub = redis.createClient(); io.sockets.on('connection', function (socket) { var sub = redis.createClient(); sub.on("message", function(pattern, data){ data = JSON.parse(data); socket.send(JSON.stringify({ type: "chat", key: pattern, nick: data.nickname, message: data.text })) } }); socket.on('message', function (messageData) { store.incr("messageNextId", function(e, messageId) { var room = "" var from = messageData.clientId > socket.nickname ? socket.nickname : messageData.clientId; var to = messageData.clientId < socket.nickname ? socket.nickname : messageData.clientId; room = from + ":" + to; var message = { id: messageId, nickname: socket.nickname, text: messageData.text }; store.rpush("rooms:" + room, JSON.stringify(message), function(e, r) { pub.publish(room, JSON.stringify(message)) }); }); });
As you can see, I am creating a new redis subscriber for each connection. In other sample chats, client-client redis is created globally. And there are only three connections all the time, and this solves their problem, because when the publisher publishes a message, all connected clients must receive it. But I have a limitation. I want to open a chat session between two users, and only these users should be subscribers. The code above works as I would like, but I do not know if it is normal for redis to create a new client-subscriber for each connection.
It would be great to hear your suggestions. Thank you in advance.
Ali ErsΓΆz Apr 13 2018-12-12T00: 00Z
source share