Skip to content

Redis - Pub & Sub

Redis also has a real-time messaging system where senders (publishers) can send messages to receivers (subscribers). All the messages are sent using something called a channel.

This feature is helpful to for example create a chat or real-time analytics implementation.

Learn more about pub & sub

Subscribing to a Channel

First, before we can publish a message to a channel, there needs to be someone subscribed to the channel. This subscriber or these subscribers will watch publications made into the channel.

One interesting thing is that one can also subscribe to multiple channels at the same time. This can be achieved by passing all the channels as parameters for the command.

Example usage:

Text Only
SUBSCRIBE myapp.chat#3 myapp.chat#150
Example Output
1) "subscribe"
2) "myapp.chat#3"
3) (integer) 1
1) "subscribe"
2) "myapp.chat#150"
3) (integer) 2

Note that in order to publish messages into the channel, you would now need to open a new terminal window.

Publishing to a Channel

The command PUBLISH can be used to publish a message to the given channel.

Example usage:

Text Only
PUBLISH myapp.chat#3 "Aleksi: Hello!"
Example Output
1) "message"
2) "myapp.chat#3"
3) "Aleksi: Hello!"

Viewing all Active Channels

The command PUBSUB channels can be used to see all active channels listening for messages.

Example usage:

Text Only
PUBSUB channels
Example Output
1) "myapp.chat#150"
2) "myapp.chat#3"

Usage Examples of Pub / Sub

Redis Pub / Sub can work very well with scenarios like these:

  • Real-time Analytics
  • Chat messages
  • Multiplayer games for notifying of other player actions
  • ... And much more!