Redis Publish Subscribe
Redis Publish Subscribe (pub/sub) is a messaging communication pattern: the sender (pub) sends a message, and the receiver (sub) receives the message.
Redis clients can subscribe to any number of channels.
The diagram below shows the channel channel1
, and the relationship between this channel and three clients — client2
, client5
, and client1
:
When a new message is sent to channel1
via the PUBLISH
command, this message is sent to the three clients subscribed to it:
Example
The following example demonstrates how publish-subscribe works, requiring two redis-cli
clients to be opened.
In our example, we created a subscription channel named tutorialproChat:
First redis-cli Client
redis 127.0.0.1:6379> SUBSCRIBE tutorialproChat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "tutorialproChat"
3) (integer) 1
Now, let's reopen another redis client and publish two messages to the same channel tutorialproChat
, the subscriber will receive the messages.
Second redis-cli Client
redis 127.0.0.1:6379> PUBLISH tutorialproChat "Redis PUBLISH test"
(integer) 1
redis 127.0.0.1:6379> PUBLISH tutorialproChat "Learn redis by tutorialpro.org"
(integer) 1
# The subscriber's client will display the following messages
1) "message"
2) "tutorialproChat"
3) "Redis PUBLISH test"
1) "message"
2) "tutorialproChat"
3) "Learn redis by tutorialpro.org"
GIF demonstration as follows:
-
Start the local Redis service and open two redis-cli
clients.
-
In the first redis-cli client, enter SUBSCRIBE tutorialproChat
, meaning to subscribe to the tutorialproChat
channel.
-
In the second redis-cli client, enter PUBLISH tutorialproChat "Redis PUBLISH test"
to send a message to the tutorialproChat
channel, at which point the first redis-cli
client will see the test message sent by the second redis-cli
client.
Redis Publish Subscribe Commands
The table below lists common Redis publish-subscribe commands:
No. | Command and Description |
---|---|
1 | PSUBSCRIBE pattern [pattern ...] <br>Subscribe to one or more channels that match the given patterns. |
2 | PUBSUB subcommand [argument [argument ...]] <br>Check the status of the publish-subscribe system. |
3 | PUBLISH channel message <br>Send a message to the specified channel. |
4 | PUNSUBSCRIBE [pattern [pattern ...]] <br>Unsubscribe from all channels that match the given patterns. |
5 | SUBSCRIBE channel [channel ...] <br>Subscribe to one or more channels. |
6 | UNSUBSCRIBE [channel [channel ...]] <br>Unsubscribe from the specified channels. |