Welcome back! In this lesson, we will dive into another powerful feature of Redis: publish/subscribe (pub/sub) messaging. This topic builds on our understanding of Redis and introduces a dynamic way to enable real-time communication within your applications.You will learn how to set up and use Redis pub/sub messaging to send and receive messages between different parts of your application. This is useful for creating real-time features like notifications, chat systems, or live updates.
Let's look at how you can set up a simple pub/sub system in the code snippet below:
php1<?php 2require 'vendor/autoload.php'; 3 4use Predis\Client; 5 6// values to use in the program 7$messageLimit = 10; 8$messagePrefix = "my-message-"; 9$channel = "my-channel"; 10 11// two clients, one as the publisher, the other as the subscriber 12$publisher = new Client(); 13$subscriber = (new Client())->pubSubLoop(); 14 15// subscribing to the relevant channel 16$subscriber->subscribe($channel); 17 18// publishing 10 messages to the relevant channel 19for ($i = 1; $i <= $messageLimit; $i++) { 20 $publisher->publish($channel, $messagePrefix.$i); 21} 22 23// loop reading incoming messages 24foreach($subscriber as $message) { 25 echo "Message received in channel [$message->channel]:\n"; 26 echo " [ KIND => $message->kind ]\n"; 27 echo " [ PAYLOAD => $message->payload ]\n\n"; 28 // the check here ensures we break the loop when we reach the last message 29 // otherwise the program will wait for the next message indefinitely 30 if ($message->payload == $messagePrefix.$messageLimit) { 31 break; 32 } 33} 34 35?>
The code demonstrates a simple pub/sub system, where a publisher sends messages to a channel and a subscriber listens and processes these messages in real-time. Let's break it down:
- We start by requiring the
vendor/autoload.php
to load the Predis library. - We define variables for the message limit, message prefix, and channel name.
- We create two
Predis\Client
objects: one for publishing messages and another for subscribing to the channel. - The subscriber client subscribes to the specified channel using the
subscribe
method. - We publish a series of messages to the channel using a loop, appending a number to the message prefix.
- The subscriber enters a loop to listen for incoming messages on the channel.
- For each message received, we print the channel name, message kind, and payload.
- A condition checks if the last message has been received to break the loop and prevent indefinite waiting.
The responses ready in this particular example would look like this:
Plain text1Message received in channel [my-channel]: 2 [ KIND => subscribe ] 3 [ PAYLOAD => 1 ] 4 5Message received in channel [my-channel]: 6 [ KIND => message ] 7 [ PAYLOAD => my-message-1 ] 8 9// ...multiple messages... 10 11Message received in channel [my-channel]: 12 [ KIND => message ] 13 [ PAYLOAD => my-message-10 ]
When you subscribe to a channel in Redis, the first message received is a notification confirming the subscription itself. This is followed by any subsequent messages published to the channel.
It's important to note that while this example demonstrates both publishing and subscribing within the same file for simplicity, in real-world applications, publishers and subscribers are typically handled by different components or services.
This separation allows for more modular and scalable application architecture, where different parts of the system can independently publish or listen for messages as needed.
We should also note that Redis' publish/subscribe system follows a fire-and-forget approach, meaning:
- Messages are not stored — subscribers must be actively listening when a message is published.
- Each message is sent to all active subscribers of a channel at the moment of publishing.
- Redis does not guarantee message delivery if a subscriber disconnects before receiving a message.
The pub/sub messaging model is essential for enabling real-time communication in modern applications. Whether it's sending notifications to users, creating chat applications, or updating dashboards live, pub/sub can help you achieve these goals effortlessly.
Here's why mastering pub/sub messaging in Redis is important:
- Real-Time Communication: You can update parts of your application immediately as events occur, providing a seamless user experience.
- Decoupled Architecture: Senders and receivers are decoupled, making your application more modular and easier to maintain.
- Scalability: Easily scale your application by adding more subscribers or publishers without changing your core logic.
Mastering pub/sub messaging in Redis will enable you to build responsive, scalable, and maintainable applications. Ready to see it in action? Let’s head to the practice section and start coding!