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 using Java. 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 with Java and the Lettuce library. Specifically, we'll cover:

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

Here is a quick refresher on how Pub/Sub works in Redis using Java and the Lettuce library:

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.pubsub.RedisPubSubAdapter;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;

public class Main {

    public static void main(String[] args) {
        // Connect to Redis
        RedisClient redisClient = RedisClient.create("redis://localhost:6379/");
        StatefulRedisConnection<String, String> publishConnection = redisClient.connect();
        StatefulRedisPubSubConnection<String, String> pubSubConnection = redisClient.connectPubSub();
        
        // Subscribe to a channel
        subscribeToChannel(pubSubConnection, "chat_room");

        // Publish a message
        publishMessage(publishConnection, "chat_room", "alice", "Hello everyone!");

        // Close connections
        publishConnection.close();
        pubSubConnection.close();
        redisClient.shutdown();
    }

    // Function to publish messages to a channel
    private static void publishMessage(StatefulRedisConnection<String, String> connection, String channel, String user, String text) {
        RedisCommands<String, String> sync = connection.sync();
        String message = String.format("{\"user\":\"%s\", \"text\":\"%s\"}", user, text);
        sync.publish(channel, message);
    }

    // Function to subscribe to a channel and handle incoming messages
    private static void subscribeToChannel(StatefulRedisPubSubConnection<String, String> connection, String channel) {
        connection.addListener(new RedisPubSubAdapter<String, String>() {
            @Override
            public void message(String channel, String message) {
                System.out.println("Received message: " + message);
            }
        });

        RedisPubSubCommands<String, String> sync = connection.sync();
        sync.subscribe(channel);
    }
}

In this code, we establish a connection to Redis. The subscribeToChannel function sets up the subscription and listens for incoming messages. The publishMessage function sends a message to the specified channel. Messages are processed and printed to the console by the RedisPubSubListener, demonstrating the real-time notification system in action.

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!

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