监听频道redis在node.js中

时间:2013-11-25 13:50:58

标签: node.js redis socket.io

有一个简单的代码窃听频道萝卜。

redisClient = redis.createClient();
redisDummyPublishClient = redis.createClient();
//redisClient.auth("25c9721b4e579fc5af961f944e23f46f");


//look for connection errors and log
redisClient.on("error", function (err) {
    console.log("error event - " + redisClient.host + ":" + redisClient.port + " - " + err);
});


var channels_active = [];
io.sockets.on('connection', function (socket) {
    redisClient.on('ready', function() {
    redisClient.psubscribe('*');
  });


  function CreateSocketsAccept (eventNameListen, channel, message){
    var obj = { channel : channel, message : message}
      for (i in eventNameListen) {
          io.sockets.in(channel).emit(eventNameListen[i], obj);
       } 
    }

  redisClient.on('pmessage', function(pattern, channel, message) {
    console.log(channel);
    CreateSocketsAccept(channels_active, channel, message);
  });     

});

setInterval(function() {
  var no = Math.floor(Math.random() * 100);
  redisDummyPublishClient.publish('478669c7fa549970e36eac591cdca62e', 'Generated random no ' + no);
}, 5000);

从PHP发送数据:

$this->load->library( 'rediska_connector' );
// Other way to publish
$rediska = new Rediska();
$rediska->publish('realtime', 'PHP SENDING');

问题是,为什么不向控制台输出可用频道的名称?

1 个答案:

答案 0 :(得分:1)

据我所知,你不能听所有频道......

如果您想订阅某个模式,则需要使用psubscribe

redisClient.psubscribe('*');

而不是收听message个事件,请听取pmessage个事件:

redisClient.on('pmessage', function(pattern, channel, message) {
  console.log(channel);
});

(感谢@DidierSpezia纠正我:)

编辑:您不能将socket.io和Redis客户端混合在一起,您需要将Redis代码移到socket.io处理程序之外:

// No need for this because it's doing nothing:
// io.sockets.on('connection', function(socket) { ... });

redisClient.on('ready', function() {
  redisClient.psubscribe('*');
});

function CreateSocketsAccept (eventNameListen, channel, message){
  var obj = { channel : channel, message : message}
  for (i in eventNameListen) {
    io.sockets.in(channel).emit(eventNameListen[i], obj);
  }
}

redisClient.on('pmessage', function(pattern, channel, message) {
  console.log(channel);
  CreateSocketsAccept(channels_active, channel, message);
});
相关问题