Redis command o...login
Redis command operation Chinese manual
author:php.cn  update time:2022-04-12 14:07:28

Redis publish and subscribe


Redis publish and subscribe (pub/sub) is a message communication model: 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 relationship between channel channel1 and the three clients that subscribe to this channel - client2, client5 and client1:

pubsub1

When there is a new message through the PUBLISH command When sent to channel channel1, this message will be sent to the three clients that subscribe to it:

pubsub2

Example

The following example demonstrates how publish and subscribe works. . In our example, we created a subscription channel named redisChat:

redis 127.0.0.1:6379> SUBSCRIBE redisChat

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

Now, we first restart a redis client, and then publish two messages in the same channel redisChat, the subscriber You can 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.cc"

(integer) 1

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

Redis publish and subscribe commands

The following table lists the common commands for redis publish and subscribe:

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

php.cn