Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Redis Publish/Subscribe

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"

  1. "runoobChat"

  2. "Redis PUBLISH test"

 1) "message"

  1. "runoobChat"

  2. "Learn redis by runoob.com"

The gif demonstration is as follows:


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.