【问题标题】:Redis and socket to send to only some clientRedis 和套接字仅发送到某些客户端
【发布时间】:2023-03-13 09:00:01
【问题描述】:

我在node.js 有这样的服务器:

socket.on('connection', function(client) {
        const subscribe = redis.createClient(6379, '127.0.0.1')

        subscribe.psubscribe('kitchen_*');

        subscribe.on("pmessage", function(pattern, channel, message) {
            client.emit(channel, message);
            log('msg', "received from channel #" + channel + " : " + message);
        });
});

在客户端我是这样的:

socket.on('kitchen_companyName', function (data) {
        console.log('received a message: ', data);
      });

现在我只想在客户端接收 kitchen_companyName 的消息,但即使公司名称是 kitchen_hello 我也收到了消息。我正在使用 pyredis 从 python 发布到 redis。

r = redis.StrictRedis(host='localhost', port=6379)
r.publish('kitchen_'+request.user.user_company, message)

【问题讨论】:

    标签: python node.js redis socket.io


    【解决方案1】:

    您可以尝试添加条件来检查通道并仅向该通道发出,

    subscribe.on("pmessage", function(pattern, channel, message) {
        if(channel == "kitchen_companyName") {
          client.emit(channel, message);
          log('msg', "received from channel #" + channel + " : " + message);
        }
    });
    

    【讨论】:

    • 问题我在服务器上没有实际的频道名称。我只有在客户端上有实际的频道名称prefix after _
    • 我设法通过 redis 发送了companyName,它现在工作正常。谢谢
    【解决方案2】:

    您订阅的是所有频道,前缀为"kitchen_",请注意订阅命令中的*

    因此,任何以"kitchen_" 开头的频道发布的任何消息都会发送给您的订阅者。

    将您的订阅消息更改为"kitchen_companyName",您将只收到该频道的消息。

    请注意,您可以为一个客户订阅多个频道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2013-04-01
      • 2018-09-08
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多