节点js不会订阅具有其他名称的redis频道

时间:2017-01-27 21:02:18

标签: node.js redis socket.io

我无法让节点js识别除“消息”之外的任何其他频道。可以识别通道名称“message”,但是当我将通道名称更改为任何其他名称时,节点不会订阅并响应通道名称。

示例:

var sub = redis.createClient();

sub.subscribe('message');

sub.on('message', function (channel, data) {

   data = JSON.parse(data);
   console.log('chat', channel, data);

});

/*
* Server
*/

// Start listening for incoming client connections
io.sockets.on('connection', function (socket) {

   console.log('NEW CLIENT CONNECTED');


   socket.on('disconnect', function () {
      console.log('DISCONNECT');
    //I've tried using unsubscribe to message to fix problem
    //sub.unsubscribe('message');
   });

});

以上代码可在控制台上运行并输出:

chat message { room: 1 }
DISCONNECT
NEW CLIENT CONNECTED

以下代码未记录频道订阅日志:

  

新客户已连接   DISCONNECT

var sub = redis.createClient();

sub.subscribe('chat');

//Does not output anything to console
sub.on('chat', function (channel, data) {

   data = JSON.parse(data);
   console.log('chat', channel, data);

});

/*
* Server
*/

// Start listening for incoming client connections
io.sockets.on('connection', function (socket) {

   console.log('NEW CLIENT CONNECTED');


   socket.on('disconnect', function () {
      console.log('DISCONNECT');
    //I've tried using unsubscribe to message to fix problem
    //sub.unsubscribe('message');
   });

});

redis-cli MONITOR:

1485546938.714486 [0 127.0.0.1:49881] "info"
1485546938.717446 [0 127.0.0.1:49881] "subscribe" "message"
1485546945.902959 [0 127.0.0.1:49897] "SELECT" "0"
1485546945.903406 [0 127.0.0.1:49897] "PUBLISH" "message" "{\"room\":1}"

1485546868.850918 [0 127.0.0.1:49857] "info"
1485546868.853824 [0 127.0.0.1:49857] "subscribe" "chat"
1485546875.332391 [0 127.0.0.1:49873] "SELECT" "0"
1485546875.332861 [0 127.0.0.1:49873] "PUBLISH" "chat" "{\"room\":1}"

1 个答案:

答案 0 :(得分:2)

无论通道名称如何,参数始终为“message”。它是这样的:

sub.on("message", function (channel, message) {
  console.log("sub channel " + channel + ": " + message);
});