English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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:
The following example demonstrates how publish/subscribe works, which requires starting two redis-cli 客户端。
In our example, we created a subscription channel named w3codeboxChat:
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.
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 发布订阅常用命令:
序号 | 命令及描述 |
---|---|
1 | PSUBSCRIBE pattern [pattern ...] 订阅一个或多个符合给定模式的频道。 |
2 | PUBSUB subcommand [argument [argument ...]] 查看订阅与发布系统状态。 |
3 | PUBLISH channel message 将信息发送到指定的频道。 |
4 | PUNSUBSCRIBE [pattern [pattern ...]] 退订所有给定模式的频道。 |
5 | SUBSCRIBE channel [channel ...] 订阅给定的一个或多个频道的信息。 |
6 | UNSUBSCRIBE [channel [channel ...]] 指退订给定的频道。 |