【问题标题】:redis pub/sub model for notification system with selective pushing具有选择性推送的通知系统的 redis pub/sub 模型
【发布时间】:2014-08-25 02:32:59
【问题描述】:

我希望构建一个类似于 facebook 的通知系统,我的应用程序逻辑(发布者)会将所有用户生成的通知推送到 redis 系统。

User 1 --------------> Redis (Channel : notifications)
User 2 --------------> Redis (Channel : notifications)
User 3 --------------> Redis (Channel : notifications)

如上所示,用户 1、2、3 生成的所有活动都发送到同一个频道通知。

我有一个 node.js /socket.io 服务器作为这些通知的订阅者监听 redis。 (订阅频道通知

现在,我如何选择性地只向特定订阅者推送某些通知? 与 facebook 通知一样,我只会收到发送给我的私人消息的通知,而不是发送给其他人的消息。

提前感谢您的帮助。

【问题讨论】:

    标签: node.js redis socket.io


    【解决方案1】:

    为每个用户创建个人频道,例如,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,你如何识别每个用户?)

    【讨论】:

    • 我对 node.js 有点陌生,所以我不确定这是否正确,但是 nodejs 应用程序订阅的频道在代码中是硬编码的,对吗?那么同一个 nodejs 脚本将如何订阅不同的频道呢?用户是否可以将自定义的可识别用户信息发送到 nodejs 服务器,以便我可以使频道名称动态化?
    • @YashDesai:我更新了我对您补充问题的回答。 (*)
    猜你喜欢
    • 1970-01-01
    • 2011-09-05
    • 2017-04-03
    • 1970-01-01
    • 2017-09-12
    • 2020-02-03
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多