为每个用户创建个人频道,例如,notifications.User1、notifications.User2、...、
并让每个用户订阅他/她的频道。
(您无需担心频道的大小。)
如果用户共享一个 redis 连接,
每当连接接收到任何订阅消息时,您可能需要从频道名称中识别接收者用户。
更新:
我假设这种情况:
当用户登录您的应用时,您的 nodejs 应用可能会知道用户的 id。
然后,您的应用仅为用户订阅频道,例如:
(这是一种伪代码,我不确定 nodejs。)
onUserLoggedIn(string userId) {
...
string userChannel = "notifications.user." + userId;
// If userId == "yash",
// then userChannel == "notifications.user.yash"
redisConnection.command("subscribe", userChannel);
...
}
当您的连接收到来自您的 redis 服务器的已发布消息时:
onMessagePublished(string channel, string message) {
...
// You can get userId from channel id.
vector<string> tokens = parseTokensFromChannel(channel);
// If channel == "notifications.user.yash",
// tokens == {"notifications", "user", "yash"};
if (tokens[0] == "notifications") {
if (tokens[1] == "user") {
...
string userId = tokens[2];
onMessagePublishedForUser(userId, message);
...
} else {
...
}
...
} else {
...
}
...
}
onMessagePublishedForUser(string userId, string message) {
// You can handle the message for each user.
// I don't think your user may need it's own handling code per user.
...
}
在这种情况下,您根本不需要任何硬编码。
您的 redis 连接可以通过简单地发送命令“订阅”订阅任何 redis 频道。
我假设您的用户会将自定义的可识别用户信息(至少是用户的 id)发送到 nodejs 服务器,以便您的 nodejs 应用程序可以使频道名称动态化。
(如果你的用户不会发送用户的id,你如何识别每个用户?)