how to use the redis publish/subscribe

点点圈 提交于 2019-12-06 03:04:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19453463/how-to-use-the-redis-publish-subscribe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!