如何在“消息"侦听器上删除Redis [英] How to remove Redis on 'message' listeners

查看:119
本文介绍了如何在“消息"侦听器上删除Redis的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

典型的Redis聊天示例将如下所示(请参见 https://github.com/emrahayanoglu/Socket.io-Redis-RealTime-Chat-Example/blob/master/chatServer.js 仅作为一个示例):

A typical Redis chat example will go something like this (see https://github.com/emrahayanoglu/Socket.io-Redis-RealTime-Chat-Example/blob/master/chatServer.js for just one such example):

io.sockets.on('connection', function (client) { //websocket connection

  redis1.subscribe("chat");

  redis1.on("message", function(channel, message) {
      console.log(message);
      client.send(message);
  });

  client.on('message', function(msg) {
    redis2.publish("chat",msg.message);  
  });

  client.on('disconnect', function() {
      redis1.quit();
  });
});

但是,这里的问题是,当client'disconnect'断开连接时,redis1.on('message',FUNC(){})侦听器仍然处于连接状态.控制台将继续打印message.如果要检查redis1的事件列表,他们仍然会发现匿名函数正在侦听.

However, the issue here is that when a client 'disconnect', the redis1.on('message',FUNC(){}) listener is still attached. The console will continue to print out the message. If one were to inspect the event listners of redis1, they would still find the anonymous function listening.

问题是没有redis1.off(...)功能.那么,如何取消绑定/取消订阅/删除/删除Redis消息侦听器?

The issue is that there is no redis1.off(...) function. So, how does one unbind/unsubscribe/delete/remove the redis message listener?

注意:一个人不能只做redis1.end(),因为这样会中断其他与Websocket连接的用户的redis连接.

Note: One cannot just do redis1.end(), since that will break the redis connection for other websocket connected users.

推荐答案

我在节点REPL中找到的唯一解决方案是不使用redis.on()函数进行订阅.相反,应该使用redis.addListener()redis.removeListener()函数.另外,一定不能将匿名函数用作事件回调. 一个人可以做这样的事情:

The only solution that I've found by playing around in the node REPL is to not use the redis.on() function to subscribe. Instead, one should use the redis.addListener() and redis.removeListener() functions. In addition, one must not use anonymous functions as event callbacks. One could do something like this:

var callback = function(channel, message){

};

redis1.addListener('message', callback);

client.on('disconnect', function(){
  redis1.removeListener('message', callback);    
})

这篇关于如何在“消息"侦听器上删除Redis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆