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?
Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel. In Redis, a client can subscribe any number of channels.
Publish/subscribe messaging, or pub/sub messaging, is a form of asynchronous service-to-service communication used in serverless and microservices architectures. In a pub/sub model, any message published to a topic is immediately received by all of the subscribers to the topic.
The Publish/Subscribe pattern, also known as pub/sub, is an architectural design pattern that provides a framework for exchanging messages between publishers and subscribers. This pattern involves the publisher and the subscriber relying on a message broker that relays messages from the publisher to the subscribers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With