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:

  1. Publishing Messages: How to send notifications.
  2. Subscribing to Channels: How to receive and handle notifications.
Subscribing to a Channel

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:

// Create a pubsub instance to unsubscribe after receiving a set number of messages
JedisPubSub pubSub = new JedisPubSub() {
    private final AtomicInteger messageCount = new AtomicInteger(0);
    private final int maxMessages = 2;

    @Override
    public void onMessage(String channel, String message) {
        System.out.println("Received message on " + channel + ": " + message);

        // Unsubscribe after maxMessages have been received
        if (messageCount.incrementAndGet() >= maxMessages) {
            System.out.println("Max messages reached. Unsubscribing...");
            unsubscribe();
        }
    }
};

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:

Thread subscriberThread = new Thread(() -> {
    try {
        subscriberJedis.subscribe(pubSub, "chat_room");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        subscriberJedis.close();
    }
});
subscriberThread.start();

This thread subscribes to the "chat_room" channel and processes messages in real time.

Publishing Messages

To send notifications, we use the publishMessage method, which sends messages to the specified channel:

// Function to publish messages to a channel
public static void publishMessage(Jedis jedis, String channel, Notification message) {
    String jsonMessage = gson.toJson(message);
    jedis.publish(channel, jsonMessage);
    System.out.println("Message published by " + message.getUser() + ": " + message.getText());
}

This method converts the Notification object to JSON format and publishes it to the channel.

In the Main class, we publish messages like this:

commandJedis.publish("chat_room", "Hello from the main thread!");
commandJedis.publish("chat_room", "Another message");

Messages are published to the "chat_room" channel, where the subscriber listens and processes them.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal