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

查看:33
本文介绍了如何删除“消息"侦听器上的 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天全站免登陆