Redis SUBSCRIBE – How to subscribe to multiple channels in redis pub/sub

2 months ago Lalit Bhagtani 0

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

SUBSCRIBE Command

The SUBSCRIBE command is used to subscribe the client to one or more specified channels in redis message broker system. Once the client executes the subscribe command, it enters the subscribed state where it listens to the subscribed channels. Messages publish by other clients to specified channels will be pushed by redis to all the subscribed clients.

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

The syntax of redis SUBSCRIBE command is as follows :-

Syntax :-

redis host:post> SUBSCRIBE <channel> [ <channel> ]

Output :- 

- (array) reply of 3 elements.

Format of Pushed Message :-

A message is a array reply with three elements. The first element of the array reply is of following kind :-

  1. subscribe : It means that we have successfully subscribed to the channel given as the second element in the reply. The third argument represents the number of channels we are currently subscribed to.
  2. message : It is a message received as result of a PUBLISH command issued by another client. The second element is the name of the originating channel, and the third argument is the actual message payload.

Example :-

Redis SUBSCRIBE

References :-

  1. SUBSCRIBE Command Docs

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