Redis Pub/Sub

Redis Pub/Sub (pub/sub) is a message communication pattern: senders (pub) send messages, and subscribers (sub) receive messages.

Redis clients can subscribe to any number of channels.

The following diagram shows the relationship between channel1 and the three clients subscribed to this channel — client2, client5, and client1:

When a new message is sent to channel1 via the PUBLISH command, the message is delivered to the three clients subscribed to it:


Example

The following example demonstrates how pub/sub works. You need to open two redis-cli clients.

In our example, we created a subscription channel namedexampleChat:

First redis-cli client

redis 127.0.0.1:6379> SUBSCRIBE exampleChat

Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "exampleChat"
3) (integer) 1

Now, let's restart a Redis client, and then publish two messages to the same channel exampleChat. The subscriber will receive the messages.

Second redis-cli client

redis 127.0.0.1:6379> PUBLISH exampleChat "Redis PUBLISH test"

(integer) 1

redis 127.0.0.1:6379> PUBLISH exampleChat "Learn redis by example.com"

(integer) 1

# The subscriber's client will display the following messages
 1) "message"
2) "exampleChat"
3) "Redis PUBLISH test"
 1) "message"
2) "exampleChat"
3) "Learn redis by example.com"

The GIF demonstration is as follows:

  • Start the local Redis service and open two redis-cli clients.

  • InFirst redis-cli clientEnterSUBSCRIBE exampleChat, which means subscribe toexampleChatthe channel.

  • InSecond redis-cli clientEnterPUBLISH exampleChat "Redis PUBLISH test"Send a message to the exampleChat channel. At this point, the first redis-cli client will see the test message sent by the second redis-cli client.


Redis Pub/Sub Commands

The following table lists common Redis pub/sub commands:

No.Command and description
1PSUBSCRIBE pattern [pattern ...]
Subscribe to one or more channels matching the given pattern.
2PUBSUB subcommand [argument [argument ...]]
View the status of the subscription and publishing system.
3PUBLISH channel message
Send a message to the specified channel.
4PUNSUBSCRIBE [pattern [pattern ...]]
Unsubscribe from all channels matching the given pattern.
5SUBSCRIBE channel [channel ...]
Subscribe to the information of one or more given channels.
6UNSUBSCRIBE [channel [channel ...]]
Refers to unsubscribing from the given channel(s).
Other extensions