6

Currently I am using node.js and redis to build a app, the reason I use redis is because of the publish/subscribe feature. The app is simply to notify the manager when user comes into the user or out of room.

function publishMsg( channel , mssage){
    redisClient.publish(channel,JSON.stringify());
}

publishMsg('room/1/user/b',{'room':1,'user':'b'});
publishMsg('room/1/user/c',{'room':1,'user':'c'});
publishMsg('room/2/user/b',{'room':2,'user':'b'});
publishMsg('room/2/user/c',{'room':2,'user':'c'});

function subscribe(pattern){
    redisClient.psubscribe(pattern);
    redisClient.on('pmessage', function(pattern, channel, message){     
        console.log('on publish / subscribe   ',  pattern+"   "+channel+"    "+message+"   "+ JSON.parse( message) );
    });
}

since I want to listen to the join and disjoin event, my question is should I use two redisclient to listen these two events, like

   redisClient1.psubscribe('room/*/user/*/join');
   redisClient2.psubscribe('room/*/user/*/disjoin');

or just use one redisclient to listen and seperate the logic inside the callback

   redisClient2.psubscribe('room/*/user/*');

I know these two ways are possible, But I don't know how in reality people use them, in which condition?

user824624
  • 7,077
  • 27
  • 106
  • 183

1 Answers1

11

You can safely reuse the same Redis connection to subscribe to multiple channels, but you cannot use the same connection to perform other (non subscription-related) tasks. The Redis documentation states:

Once the client enters the subscribed state it is not supposed to issue any other commands, except for additional SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE and PUNSUBSCRIBE commands.

I always use a single Redis connection in Node to listen to subscribed channels.

Tamas Czinege
  • 118,853
  • 40
  • 150
  • 176