English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Redis publish and 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 publishing and subscribing work, which requires starting two redis-cli client.
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 client.
inthe first redis-cli clientEnter SUBSCRIBE w3codeboxChat, which means to subscribe to w3codeboxChat channel.
inthe second redis-cli clientEnter PUBLISH w3codeboxChat "Redis PUBLISH test" to w3codeboxChat channel at this time, in the first redis-The cli client will see the message sent by the second redis-Test message sent by the cli client.
The following table lists the commonly used redis pub/sub commands:
Serial Number | Command and Description |
---|---|
1 | PSUBSCRIBE pattern [pattern ...] Subscribe to one or more channels that match the given pattern. |
2 | PUBSUB subcommand [argument [argument ...]] View the status of the subscription and publishing system. |
3 | PUBLISH channel message Send information to the specified channel. |
4 | PUNSUBSCRIBE [pattern [pattern ...]] Unsubscribe from all channels matching the given pattern. |
5 | SUBSCRIBE channel [channel ...] Subscribe to information of one or more specified channels. |
6 | UNSUBSCRIBE [channel [channel ...]] Unsubscribe from the specified channel. |