Let’s see how to implement the Redis Pub-Sub model in this article. For diversity, we will not opt for any programming language. Instead, we will use raw Redis commands to accomplish this.
How Pub-Sub Works
The Pub-Sub model is pretty straightforward. We start by creating a channel to which a user can subscribe.
Once a user subscribes to a channel, they cannot send any commands to the server. However, the channel’s creator (publisher) can send commands and publish messages to the server.
Keep in mind that a single user can subscribe to multiple channels simultaneously.
Subscribing to a Channel
To implement Pub-Sub, open the terminal and log in to the Redis CLI. We can now subscribe to a channel using the command SUBSCRIBE and the name of the channels to subscribe to.
Example:
The command above should subscribe to channels called chat_room_1 and chat_room_2.
At this point, the user can read any message that is published to these channels.
Publishing Messages
Next, open a new terminal window and connect to the Redis server. Once connected, we can publish messages to the channels as:
(integer) 1
The command above should publish the message to channel one, where the subscribers can receive it.
Go to the subscriber terminal session to check it.
The message received in the subscriber window is comprised of three main components:
- Notice which indicates the message.
- The channel to which the message was sent.
- The message content.
NOTE: Publishing a message to a channel that does not exist (meaning there are no subscribers) forces Redis to discard the message and return 0.
Example:
(integer) 0
Conclusion
This article covers how to use the Redis Pub-Sub model through a simple tutorial. By using raw Redis commands and abstaining from programming language, readers should be able to send and receive messages with Redis Pub-Sub at the end of this article.