Redis和socket只发送给一些客户端

时间:2014-05-13 12:49:01

标签: python node.js redis socket.io

我在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)

2 个答案:

答案 0 :(得分:0)

您可以尝试添加条件来检查频道并仅向该频道发送

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

答案 1 :(得分:0)

您订阅的所有频道都以"kitchen_"为前缀,在订阅命令中注明*

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

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

请注意,您可以将一个客户端订阅到多个渠道。