Databases 10 min read

Redis Pub/Sub: Concepts, Commands, and Java Implementation

This article introduces Redis Pub/Sub messaging, explains its purpose of decoupling publishers and subscribers, demonstrates command-line operations such as PUBLISH, SUBSCRIBE, PSUBSCRIBE, and provides a complete Java Spring Boot example using Jedis to publish and subscribe to channels.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Redis Pub/Sub: Concepts, Commands, and Java Implementation

Introduction

Redis Pub/Sub is an event‑driven messaging mechanism that decouples publishers from subscribers. A channel is the logical name used for publishing; any subscriber listening to that channel receives the messages in real time.

Besides Pub/Sub, Redis can also implement a message queue using list structures.

Command‑line Practice

Assuming Redis is installed and running, the following commands illustrate basic Pub/Sub operations.

Publish a Message

Use the PUBLISH command: PUBLISH test "haha" The command returns an integer indicating the number of subscribers that received the message (0 if none).

Subscribe to a Channel

In another terminal, run: SUBSCRIBE test The subscriber receives three fields for each message: the message type, the channel name, and the message content.

Unsubscribe

To stop receiving messages:

UNSUBSCRIBE test

Pattern Subscribe

Subscribe to multiple channels matching a pattern with PSUBSCRIBE: PSUBSCRIBE ldc* Unsubscribe from a pattern with PUNSUBSCRIBE:

PUNSUBSCRIBE ldc*

Inspect Subscriptions

List active channels matching a pattern: PUBSUB CHANNELS ldc* Get subscriber count for a specific channel: PUBSUB NUMSUB test Get the number of pattern subscriptions:

PUBSUB NUMPAT

Java Implementation

Add Jedis dependency to a Spring Boot project:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

Create a Publisher class that reads console input and publishes messages to a channel.

package com.ldc.org.myproject.demo.redis;

import java.io.*;
import redis.clients.jedis.*;

public class Publisher extends Thread {
    private final JedisPool jedisPool;
    private String name;
    public Publisher(JedisPool jedisPool, String name) {
        this.jedisPool = jedisPool;
        this.name = name;
    }
    @Override
    public void run() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Jedis resource = jedisPool.getResource();
        while (true) {
            try {
                String message = reader.readLine();
                if (!"exit".equals(message)) {
                    resource.publish(name, "Publisher:" + Thread.currentThread().getName() + " message:" + message);
                } else {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Implement a Subscriber extending JedisPubSub and override onMessage, onSubscribe, and onUnsubscribe to print received information.

package com.ldc.org.myproject.demo.redis;

import redis.clients.jedis.JedisPubSub;

public class Subscriber extends JedisPubSub {
    @Override
    public void onMessage(String channel, String message) {
        System.out.println("Channel:" + channel + "  Received:" + message);
    }
    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("Subscribed to:" + channel + "  Count:" + subscribedChannels);
    }
    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println("Unsubscribed from:" + channel + "  Count:" + subscribedChannels);
    }
}

Run the publisher and subscriber in separate threads (or via a thread pool) to see real‑time message exchange.

public class TestPublisher {
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("192.168.163.155");
        Publisher publisher = new Publisher(jedisPool, "ldc");
        publisher.start();
    }
}
public class TestSubscriber1 {
    public static void main(String[] args) throws InterruptedException {
        JedisPool jedisPool = new JedisPool("192.168.163.155", 6379);
        Subscriber subscriber = new Subscriber();
        SubThread thread = new SubThread(jedisPool, subscriber, "ldc");
        thread.start();
        Thread.sleep(600000);
        subscriber.unsubscribe("ldc");
    }
}

The article concludes that Redis Pub/Sub is a simple yet powerful tool for real‑time communication, and the next topic will cover Redis clustering.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaredisJedisMessagingpub/sub
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.