Redis publish and subscribe (pub/sub) is a message communication mode:发送者(pub)发送消息,订阅者(sub)接收消息。
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:
When a new message is sent to channel channel1 through the PUBLISH command, this message will be sent to subscribe to it The three clients:
actual case
The following example demonstrates how publish and subscribe 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, we first restart a redis client, and then publish two messages in the same channel redisChat, and subscribers can receive the messages.
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 runoob.com"
(integer) 1
# 订阅者的客户端会显示如下消息
1) "message"
2) "redisChat"
3) "Redis is a great caching technique"
1) "message"
2) "redisChat"
3) "Learn redis by runoob.com"
Redis publish and subscribe commands
The following table lists the commonly used redis publish and subscribe commands: