Real Time Notifications
Implementing Pub/Sub for Notifications
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 will enable our system to send and receive messages instantaneously.
What You'll Build
In this unit, we'll focus on creating a simple real-time notification system using Redis Pub/Sub. Specifically, we'll cover:
- Publishing messages: how to send notifications.
- Subscribing to channels: how to receive and handle notifications.
We'll implement a complete C++ program using Boost.Redis that demonstrates both publishing and subscribing. The example will:
- Create separate connections for subscribing and publishing, which is required for Pub/Sub.
- Subscribe to a channel and listen for messages asynchronously.
- Publish a JSON-formatted message to that channel.
- Process and display the received message.
Messages will use JSON format for structured data:
Section 1: Includes, aliases, and the receive loop
This first section sets up the headers, type aliases, and the function that listens for Pub/Sub messages.
This section prepares the program to receive messages from Redis.
It includes the libraries for:
- Redis communication with Boost.Redis
- asynchronous execution with Boost.Asio
- JSON parsing with
nlohmann::json
It also defines start_receive_loop, which waits for push messages on the subscriber connection.
The function creates a generic_response object and gives it to the connection with set_receive_response(). Then it calls async_receive() to wait for the next Pub/Sub message without blocking the program.
For Pub/Sub in RESP3, a published message arrives in this structure:
The code checks that structure, extracts the channel and payload, parses the JSON message, and prints the sender and text. If the push message is something else, such as a subscribe confirmation, the function starts listening again.
This receive loop is what allows the subscriber connection to keep handling incoming messages asynchronously.
