Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

node.js - How to remove Redis on 'message' listeners

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();
  });
});

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...