Using the same redis.createClient() instance for publish and subscribe

情到浓时终转凉″ 提交于 2019-12-23 18:21:45

问题


I'm working with redis to publish and subscribe messages between socket.io clients, when client connects to the server (io.sockets.on('connection', function(socket){...});) i'm creating a subscribe variable using redis.createClient() and then using the subscribe function to subscribe the client to channel.

My question is if its right to use the same subscribe variable to do a publish action? or it's important to create another instance with redis.createClient() for publishing messages so i will have 2 instances, one for publishing and one for subscribing...

Thanks


回答1:


From the Redis docs:

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.

For this reason, you'll need two clients, one for subscribing and one for publishing (and potentially other commands).




回答2:


By subscribe variable you mean the object that redis.createClient() returns ? If yes, from the documentation, When a client issues a SUBSCRIBE or PSUBSCRIBE, that connection is put into "pub/sub" mode. At that point, only commands that modify the subscription set are valid. so yes, you cannot publish to a client where you subscribed first, that would issue a Error: Connection in pub/sub mode, only pub/sub commands may be used error.

You do need to create one client for subscriptions (which can be modified on the fly), and one client to publish. When the subscriptions for a client are free, you have your normal state again.



来源:https://stackoverflow.com/questions/12029540/using-the-same-redis-createclient-instance-for-publish-and-subscribe

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