Pub/Sub Messaging with Jedis

Pub/Sub Messaging

Welcome back! In this lesson, we’ll explore Redis Publish/Subscribe (Pub/Sub) messaging, a powerful feature for real-time communication. Pub/Sub enables applications to send and receive messages efficiently, making it ideal for features like notifications, chat systems, and live dashboards.

Understanding Pub/Sub Messaging

Redis Pub/Sub operates on a simple yet effective messaging pattern:

  • Publishers send messages to a named channel.
  • Subscribers listen for messages on the channel and process them as they arrive.

This decoupled architecture allows publishers and subscribers to operate independently, enhancing scalability and modularity. Pub/Sub is well-suited for use cases like broadcasting events or propagating updates across distributed systems.

Setting Up a Subscriber

The subscriber listens to a specific channel and processes incoming messages. In Redis, this is handled using the SUBSCRIBE method, which blocks until explicitly unsubscribed.

Java
// Subscriber thread
Thread subscriber = new Thread(() -> {
    try (Jedis jedis = new Jedis("localhost", 6379)) {
        JedisPubSub jedisPubSub = new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                System.out.println("Received message: " + message);
            }
        };
        // Subscribe to the "notifications" channel
        jedis.subscribe(jedisPubSub, "notifications");
    } catch (Exception e) {
        e.printStackTrace();
    }
});
subscriber.start();

The subscriber connects to the notifications channel and listens for messages. When a message arrives, the overridden onMessage method processes it and outputs the message content.

Sending Messages with a Publisher

The publisher sends messages to a channel, which are then received by all active subscribers. In Redis, this is done using the PUBLISH method.

Java
// Publisher thread
Thread publisher = new Thread(() -> {
    try (Jedis jedis = new Jedis("localhost", 6379)) {
        Thread.sleep(1000); // Allow subscriber to connect
        jedis.publish("notifications", "Hello, Redis!");
    } catch (Exception e) {
        e.printStackTrace();
    }
});
publisher.start();

The publisher sends the message "Hello, Redis!" to the notifications channel. A brief delay ensures the subscriber is ready before publishing.

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