Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Redis publishes subscriptions


May 16, 2021 Redis


Table of contents


Redis publishes subscriptions

Redis publishing subscriptions (pub/sub) are a mode of message communication: the sender (pub) sends a message and the subscriber (sub) receives the message.

The Redis client can subscribe to any number of channels.

The following illustration shows the relationship between channel 1 and the three clients that subscribe to the channel - client2, client5, and client1:

Redis publishes subscriptions

Redis publishes subscriptions

When a new message is sent to channel 1 via the PUBLISH command, the message is sent to the three clients that subscribe to it:

Redis publishes subscriptions


The following example shows how a publishing subscription works. In our example, we created a subscription channel called redisChat :

redis 127.0.0.1:6379> SUBSCRIBE redisChat

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

Now, let's re-open the redis client, and then publish the message twice on the same channel, redisChat, and the subscriber will receive the message.

redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"

(integer) 1

redis 127.0.0.1:6379> PUBLISH redisChat "Learn redis by w3cschool.cn"

(integer) 1

# 订阅者的客户端会显示如下消息
1) "message"
2) "redisChat"
3) "Redis is a great caching technique"
1) "message"
2) "redisChat"
3) "Learn redis by w3cschool.cn"

Redis publishes subscription commands

The following table lists common commands for redis publishing subscriptions:

Serial number Commands and descriptions
1 PSUBSCRIBE pattern [pattern ...]
Subscribe to one or more channels that conform to a given pattern.
2 PUBSUB subcommand [argument [argument ...]]
View the status of the subscription and publishing system.
3 PUBLISH channel message
Send the information to the specified channel.
4 PUNSUBSCRIBE [pattern [pattern ...]]
Desubscribe channels for all given modes.
5 SUBSCRIBE channel [channel ...]
Subscribe to information for one or more channels given.
6 UNSUBSCRIBE [channel [channel ...]]
Refers to the desubscribe of a given channel.