Redis PSUBSCRIBE – How to subscribe to multiple patterns in redis pub/sub

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to subscribe to multiple patterns in redis message broker system using redis-cli.

PSUBSCRIBE Command

The PSUBSCRIBE command is used to subscribe the client to one or more patterns, in order to receive all the messages publish to channels whose names matches the specified patterns. The patterns are specified in glob-style. Similar to SUBSCRIBE command, once the client executes the psubscribe command, it enters the subscribed state where it listens to the subscribed patterns. Messages publish by other clients to channel whose name matches any of the subscribed patterns will be pushed by redis to client.

When the client is in subscribed state, it is not supposed to execute any other commands, except for SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE, PUNSUBSCRIBE, PING and QUIT commands. In redis-cli, once the client is in subscribed state, the client will not accept any other commands and can only quit the state with Ctrl + C.

Glob Style Patterns :-

  1. * wildcard :- It matches zero or more of any characters including spaces, for example foo* matches to fooccc, foo, fooq.
  2. ? wildcard :- It matches exactly one of any characters including spaces, for example f?0 matches to fao, fbo, fco.
  3. [list] wildcard :- It matches exactly one character from the list, for example f[abc]0 matches to fao, fbo, fco.

Use \ to escape special characters.

The syntax of redis PSUBSCRIBE command is as follows :-

Syntax :-

redis host:post> PSUBSCRIBE <pattern> [ <pattern> ]

Output :- 

- (array) reply of 3 elements, when PSUBSCRIBE command is executed in the client.
- (array) reply of 4 elements, When message is received by the client. 

Format of Pushed Message :-

The first element of the array reply is of following kind :-

  1. psubscribe ( 3 elements ) : It means that we have successfully subscribed to the pattern given as the second element in the reply. The third element represents the number of patterns we are currently subscribed to.
  2. pmessage ( 4 elements ) : It is a message received as result of a PUBLISH command issued by another client. The second element is the original pattern matched, the third element is the name of the originating channel, and the fourth element is the actual message payload.

Example :-

Redis PSUBSCRIBE

References :-

  1. PSUBSCRIBE Command Docs

That’s all for how to subscribe to one or more patterns in redis message broker using redis-cli using redis psubscribe. If you liked it, please share your thoughts in comments section and share it with others too.