如何devise即时通讯系统的redis pub / sub?

我是redis pub / sub的新手。 我在系统中有一个像IM一样的聊天工具。 所以我想用redis pub / sub。 正如我已经检查过的样本大多是基于聊天室devise的。 在我的系统中,我将有多个用户之间的聊天室,

A:B A:C D:C E:F 

所以,上面的线是房间。 我已经实现了像下面的node.js的服务器;

 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)) }); }); }); 

正如你所看到的,我正在为每个连接创build一个新的redis订户。 在其他聊天室样本中,redis订阅者客户端是全局创build的。 而且一直只有三个连接,解决了他们的问题,因为当发布者发布消息时,所有连接的客户端都应该得到它。 但是我在这里有一个限制。 我想打开两个用户之间的聊天会话,只有这些用户应该是用户。 上面的代码正如我所愿,但我不知道是否可以为每个连接创build一个新的订阅服务器客户端。

听到你的build议,真是太好了。 提前致谢。

与往常一样,您需要为您自己的用例标准化这样的事情 – 不可能提供一般build议。 您可能需要增加系统上或redis用户的系统上打开文件的最大数量。 当然,这也适用于运行您的Web服务器的用户。

也就是说,当用户离开时,应该确保监听socket.on('disconnect')quit() redis用户。 您可能也有兴趣知道,socket.io有一个redis后端,它利用redis pub / sub,它也有房间的概念,所以你可以节省自己一些麻烦,因为你已经取决于套接字.IO。

编辑:经过快速检查,我收到了来自Redis的991个订阅者的错误消息:

 Ready check failed: Error: Error: ERR max number of clients reached 

这里是从默认的redis.conf

 # Set the max number of connected clients at the same time. By default # this limit is set to 10000 clients, however if the Redis server is not # able ot configure the process file limit to allow for the specified limit # the max number of allowed clients is set to the current file limit # minus 32 (as Redis reserves a few file descriptors for internal uses). # # Once the limit is reached Redis will close all the new connections sending # an error 'max number of clients reached'. # # maxclients 10000 

我的系统(Ubuntu 11.11)带有1024的默认nofile限制,所以我的快速testing应该在992个连接的客户端之后失败,这似乎是正确的(我也有一个发布者的客户端)。 我的build议是检查你的nofile限制(在我的系统上是在/etc/security/limits.{conf,d/*}和你的redis maxclients设置,然后是基准testing,基准testing,基准testing!