【问题标题】:Listening channels redis in node.js在 node.js 中监听通道 redis
【发布时间】:2013-11-26 03:46:40
【问题描述】:

有这么简单的密码窃听频道萝卜。

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');

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

【问题讨论】:

    标签: node.js redis socket.io


    【解决方案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);
    });
    

    【讨论】:

    • 嗯,你可以 - 但你需要使用订阅模式(即 psubscribe 并收听“pmessage”)
    • @DidierSpezia 感谢您的更正 :) 我会看看 node-redis 是否支持 PSUBSCRIBE 并相应地编辑我的答案。
    • 谢谢,但不行。我在上面编辑了有问题的代码,请看,这里是 console.log(channel);
    • 你能解释一下,我会设置什么来代替参数“模式”吗?
    • @OlegPonomarchuk 你没有设置它,它是导致pmessage 事件调用处理程序的模式(在这种情况下为*)。如果您使用psubscribe 订阅模式test*,则pattern 参数也将包含test*
    猜你喜欢
    • 2015-10-01
    • 2011-09-13
    • 1970-01-01
    • 2015-10-15
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2013-01-17
    相关资源
    最近更新 更多