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

Redis 发布订阅

Redis publish/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 publish/subscribe works, which requires starting two redis-cli 客户端。

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

第一个 redis-cli 客户端

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.

第二个 redis-cli 客户端

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 客户端。

  • 第一个 redis-cli 客户端输入 SUBSCRIBE w3codeboxChat,意思是订阅 w3codeboxChat 频道。

  • 第二个 redis-cli 客户端输入 PUBLISH w3codeboxChat "Redis PUBLISH test" 往 w3codeboxChat 频道发送消息,这个时候在第一个 redis-cli 客户端就会看到由第二个 redis-cli 客户端发送的测试消息。

Redis 发布订阅命令

下表列出了 redis 发布订阅常用命令:

序号命令及描述
1PSUBSCRIBE pattern [pattern ...]
订阅一个或多个符合给定模式的频道。
2PUBSUB subcommand [argument [argument ...]]
查看订阅与发布系统状态。
3PUBLISH channel message
将信息发送到指定的频道。
4PUNSUBSCRIBE [pattern [pattern ...]]
退订所有给定模式的频道。
5SUBSCRIBE channel [channel ...]
订阅给定的一个或多个频道的信息。
6UNSUBSCRIBE [channel [channel ...]]
指退订给定的频道。