Welcome! In this unit, we will delve into implementing Pub/Sub for notifications within our Redis-based backend system project. You've already learned how to manage user data, handle transactions, and use streams for event logging. Now, we'll add another powerful feature to our project: real-time notifications using Redis Pub/Sub (publish/subscribe). This addition will enable our system to send and receive messages instantaneously.
In this unit, we'll focus on creating a simple real-time notification system using Redis Pub/Sub with PHP. Specifically, we'll cover:
- Publishing Messages: How to send notifications.
- Subscribing to Channels: How to receive and handle notifications.
Here is a quick refresher on how Pub/Sub works in Redis using PHP with the Predis
library:
Below is a PHP code example using the Predis
library to demonstrate setting up a publisher and subscriber, publishing messages to a channel, and handling incoming messages:
php1<?php 2 3require 'vendor/autoload.php'; 4 5use Predis\Client; 6 7// Values to use in the program 8$messageLimit = 10; 9$messagePrefix = "my-message-"; 10$channel = "my-channel"; 11 12// Two clients, one as the publisher, the other as the subscriber 13$publisher = new Client(); 14$subscriber = (new Client())->pubSubLoop(); 15 16// Subscribing to the relevant channel 17$subscriber->subscribe($channel); 18 19// Publishing 10 messages to the relevant channel 20for ($i = 1; $i <= $messageLimit; $i++) { 21 $publisher->publish($channel, $messagePrefix.$i); 22} 23 24// Loop reading incoming messages 25foreach($subscriber as $message) { 26 echo "Message received in channel [$message->channel]:\n"; 27 echo " [ KIND => $message->kind ]\n"; 28 echo " [ PAYLOAD => $message->payload ]\n\n"; 29 30 // The check here ensures we break the loop when we reach the last message 31 // Otherwise, the program will wait for the next message indefinitely 32 if ($message->payload == $messagePrefix.$messageLimit) { 33 break; 34 } 35} 36 37?>
In this snippet, the subscriber listens to messages on the my-channel
channel. The publisher sends messages to this channel, and the subscriber processes incoming messages, printing them to the console.
Exciting, isn’t it? Now, it's time to put this into practice. Let's implement the complete code to build our real-time notification system.
Happy coding!