May 16, 2021 Redis
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:
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:
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"
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. |