Redis Pub Sub ( Message Broker System ) – Redis Tutorial

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to use redis datastore as a publish/subscribe messaging system.

Redis Pub/Sub System

Redis implements the Publish/Subscribe messaging paradigm. According to this messaging paradigm, the sender ( publisher ) of the message are not programmed to send their message directly to a specific receiver ( subscriber ). They send ( publish ) their message to a specific channel, without the knowledge of which or if any receiver ( subscriber ) will consume the message or not. A receiver ( subscriber ), who wants to consume the message express their interest by subscribing to one or more channels, and they will receive the messages that are publish to those channels only, without the knowledge of which sender ( publisher ) had send the message.

Redis Pub Sub

In Redis terminology, sender of the message is called Publisher as they publish the message to a channel and receiver of the message is called Subscriber as they subscribe to one or more channels to consume the message. A message can contain any kind of information, it can be a simple text message or can be an information about a task. A subscriber can subscribe to any number of channels and a publish can publish its message to any channel.

This decoupling of publisher and subscriber allows scalability and flexibility.

Redis Pub Sub has no relation to Redis Key-Value database. It does not interfere with it on any level, including database numbers. So for example, if publisher publish a message on db index 10, then a subscriber on db index 1 will receive the message.

Redis Pub Sub Commands :- 

All of the important commands related to redis pub sub are as follows :-

S.No Command Description
1 PSUBSCRIBE Subscribe to one or more channels matching given pattern
2 PUBSUB Tell the state of Pub/Sub system
3 PUBLISH Publish a message to specific channel
4 PUNSUBSCRIBE Unsubscribe from one or more channels matching given pattern
5 SUBSCRIBE Subscribe to one or more channels
6 UNSUBSCRIBE Unsubscribe from one or more channels

 

Example :-

In this example, we will use three different instances of redis-cli to demonstrate the redis pub sub system where one client is subscribing to two channels C1 and C2 and other two clients are publishing messages to channel C1 and Channel C2 respectively.

 1. First client is subscribing to C1 and C2 channels

Redis-PubSubEx-1

 

2. Second client is publishing Hello message to channel C1

Redis-PubSubEx-2

 

3. Third client is publishing World message to channel C2

Redis-PubSubEx-3

 

4. First client showing pushed messages from channel C1 and C2

Redis-PubSubEx-4

References :-

  1. Pub Sub Command Docs

If you liked it, please share your thoughts in comments section and share it with others too.

Next -> Redis Pub Sub example using jedis library