My mental model was that of a 'chat', where I am subscribed to a certain channel and I can publish messages to this channel.
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.
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.
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