Redis Publish/Subscribe
Redis publish/subscribe (pub/sub) is a messaging communication pattern: the sender (pub) sends messages, and the subscriber (sub) receives messages.
A Redis client can subscribe to any number of channels.
The figure below shows the channel channel1 and the relationship between the three clients subscribing to this channel — client2, client5, and client1:
When a new message is sent to channel channel1 via the PUBLISH command, this message is delivered to the three clients subscribed to it:
Example
The following example demonstrates how publish/subscribe works; it requires two redis-cli clients to be opened.
In our example we created a subscription channel named runoobChat:
The first redis-cli client
redis 127.0.0.1:
6379
SUBSCRIBE runoobChat
Reading messages...
(
press Ctrl-C to quit
)
1
)
"subscribe"
2
)
"runoobChat"
3
)
(
integer
)
1
Now, let us reopen a redis client, then publish messages twice on the same channel runoobChat, and the subscriber will receive the messages.
The second redis-cli client
redis 127.0.0.1:6379> PUBLISH runoobChat "Redis PUBLISH test"
(integer) 1
redis 127.0.0.1:6379> PUBLISH runoobChat "Learn redis by runoob.com"
(integer) 1
The subscriber's client will display the following message
1) "message"
-
"runoobChat"
-
"Redis PUBLISH test"
1) "message"
-
"runoobChat"
-
"Learn redis by runoob.com"
The gif demonstration is as follows:
-
Start the local Redis service and open two redis-cli clients.
-
inThe first redis-cli clientInput SUBSCRIBE runoobChat, which means to subscribe to
runoobChatchannel. -
inThe second redis-cli clientInput PUBLISH runoobChat "Redis PUBLISH test" Send a message to the runoobChat channel; at this 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 the common redis publish/subscribe commands:
| No. | Command and Description |
|---|---|
| 1 | PSUBSCRIBE pattern [pattern ...] |
| Subscribe to one or more channels matching the given pattern. | |
| 2 | PUBSUB subcommand [argument [argument ...]] |
| Inspect the state of the subscription and publication system. | |
| 3 | PUBLISH channel message |
| Send a message to the specified channel. | |
| 4 | PUNSUBSCRIBE [pattern [pattern ...]] |
| Unsubscribe from all channels matching the given patterns. | |
| 5 | SUBSCRIBE channel [channel ...] |
| Subscribe to messages from one or more given channels. | |
| 6 | UNSUBSCRIBE [channel [channel ...]] |
| Unsubscribe from the given channel. |