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.
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.
To receive notifications, we set up a subscriber that listens to a specific channel. In our implementation, this is handled by the JedisPubSub class, which processes incoming messages:
This setup listens for messages on a channel and unsubscribes after receiving a certain number of messages (maxMessages). The subscriber runs in a separate thread:
This thread subscribes to the "chat_room" channel and processes messages in real time.
To send notifications, we use the publishMessage method, which sends messages to the specified channel:
This method converts the Notification object to JSON format and publishes it to the channel.
In the Main class, we publish messages like this:
Messages are published to the "chat_room" channel, where the subscriber listens and processes them.
