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.
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:
Example Output
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:
Viewing all Active Channels
The command PUBSUB channels can be used to see all active channels listening for messages.
Example usage:
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!