English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Redis Pub/Sub

Redis publish and subscribe (pub/sub) is a message communication mode: the sender (pub) sends messages, and the subscriber (sub) receives messages.

Redis clients can subscribe to any number of channels.

The following figure shows the channel channel1 , as well as the three clients that subscribe to this channel —— client2 , and client5 and client1 The relationship between

When a new message is sent to the channel channel through the PUBLISH command1 At this time, this message will be sent to the three clients that subscribe to it:

Online example

The following example demonstrates how publishing and subscribing work, which requires starting two redis-cli client.

In our example, we created a subscription channel named w3codeboxChat:

the first redis-cli client

redis 127.0.0.1:6379> SUBSCRIBE w3codeboxChat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1

Now, let's restart a redis client first, and then on the same channel w3codeboxChat publishes two messages, and the subscriber can receive the messages.

the second redis-cli client

redis 127.0.0.1:6379> PUBLISH w3codeboxChat "Redis PUBLISH test"
(integer) 1
redis 127.0.0.1:6379> PUBLISH w3codeboxChat "Learn redis by oldtoolbag.com"
(integer) 1
# The subscriber's client will display the following message
 1) "message"
2) "w3codeboxChat"
3) "Redis PUBLISH test"
 1) "message"
2) "w3codeboxChat"
3) "Learn redis by oldtoolbag.com"

The process is as follows:

  • Start the local Redis service, start two redis-cli client.

  • inthe first redis-cli clientEnter SUBSCRIBE w3codeboxChat, which means to subscribe to w3codeboxChat channel.

  • inthe second redis-cli clientEnter PUBLISH w3codeboxChat "Redis PUBLISH test" to w3codeboxChat channel at this time, in the first redis-The cli client will see the message sent by the second redis-Test message sent by the cli client.

Redis Pub/Sub Commands

The following table lists the commonly used redis pub/sub commands:

Serial NumberCommand and Description
1PSUBSCRIBE pattern [pattern ...]
Subscribe to one or more channels that match the given pattern.
2PUBSUB subcommand [argument [argument ...]]
View the status of the subscription and publishing system.
3PUBLISH channel message
Send information to the specified channel.
4PUNSUBSCRIBE [pattern [pattern ...]]
Unsubscribe from all channels matching the given pattern.
5SUBSCRIBE channel [channel ...]
Subscribe to information of one or more specified channels.
6UNSUBSCRIBE [channel [channel ...]]
Unsubscribe from the specified channel.