跨水平服务器计算 socket.io 用户

问题描述:

我有多个使用 redisstore 水平扩展的 socket.io 服务器.我已经有效地设置了房间,并且能够成功地跨服务器向房间广播等.现在我正在尝试构建一个状态页面,但我未能弄清楚如何简单地计算连接的用户数量所有服务器.

I have multiple socket.io servers scaled horizontally using a redisstore. I've got rooms setup effectively and am successfully able to broadcast to rooms across servers, etc. Now I'm trying to build a status page and what I'm failing on figuring out is how to simply count the number of users connected across all servers.

io.sockets.clients('room') 和 io.sockets.sockets 只会告诉你那台服务器上连接的客户端数量,而不是所有服务器都连接到同一个 RedisStore.

io.sockets.clients('room') and io.sockets.sockets will only tell you the number of connected clients on that one server, not all servers connected to the same RedisStore.

建议?

谢谢.

我通过让每个服务器定期在 redis 中设置一个用户计数并包含他们自己的 pid 的过期时间解决了这个问题:

I solved this by having each server periodically set a user count in redis with an expiration that included their own pid:

每个都做 setex userCount:<间隔+10>

然后状态服务器可以查询这些键中的每一个,然后获取每个键的值:

then the status server can query for each of these keys, and then get the values for each key:

对于每个 keys userCount* 做 total+=get

for each keys userCount* do total+=get <key>

因此,如果服务器崩溃或关闭,那么它的计数将在间隔+10 后从 redis 中删除

so if a server crashes or is shutdown then its counts will drop out of redis after interval+10

对丑陋的伪代码感到抱歉.:)

sorry about the ugly pseudocode. :)