Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I have a single Redis client acting as PUB and Sub in the same connection?

My mental model was that of a 'chat', where I am subscribed to a certain channel and I can publish messages to this channel.

like image 603
Draconar Avatar asked Sep 05 '11 16:09

Draconar


2 Answers

Since pub/sub is asynchronous, the published message could appear at any time, including when you are expecting the response to a command.

Although redis is single threaded, which normally prevents that sort of thing, network latency can cause some interesting effects - depending on the content of the messages, you could receive a valid response to a command before the server has actually received it.

That said, you could probably use a single connection if you really wanted to - "should not" is not the same as "can not", and redis follows a simple design philosophy of not trying to prevent you from shooting yourself in the foot. However, it is a lot easier to just open two connections to the server. If you hit connection limits with two connections per client you will probably run into problems with one connection per client fairly soon anyway.

like image 193
Tom Clarkson Avatar answered Nov 15 '22 12:11

Tom Clarkson


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. When the subscription set is empty, the connection is put back into regular mode.

If you need to send regular commands to Redis while in pub/sub mode, just open another connection.

like image 22
himanshu yadav Avatar answered Nov 15 '22 12:11

himanshu yadav