How to Use Redis Pub/Sub (Publish/Subscribe) in Java?
Publish/subscribe, also known as pub/sub, is a messaging pattern that's become a key concept in the development of high-performance, distributed applications. One of the many ways developers use the in-memory data store Redis is to make it serve as a message broker for pub/sub operations.
Java developers looking to use Redis pub/sub in their applications have a couple of options. One is to develop their own interface to Redis and its PUBLISH and SUBSCRIBE commands. The second option — the third-party client Redisson or the more advanced Redisson PRO — is much easier and streamlines the use of Redis pub/sub in Java.
What Is Pub/Sub and How Does It Work?
Before going into detail about Redisson, Redisson PRO, and their benefits for Java developers, here's what you need to know about the pub/sub messaging pattern.
Technically speaking, publish/subscribe is an asynchronous communication pattern found in modern application architectures, such as serverless apps and microservices. The four key concepts of pub/sub are:
- Message: Pub/sub's fundamental unit of communication — a self-contained, encoded data packet exchanged between parties.
- Publisher: The entity responsible for sending messages.
- Subscriber: The entity that receives messages from one or more publishers.
- Topic: A named channel that categorizes messages by subject.
The core strength of pub/sub lies in its decoupling nature. Publishers send messages to a topic without knowing which (or how many) subscribers are listening. Conversely, subscribers express interest in a specific topic and receive relevant messages without knowing the publisher's identity. This "fire-and-forget" approach promotes scalability and flexibility in modern application development.
Pub/Sub Applications
The pub/sub paradigm has nearly unlimited applications. For example, it can provide real-time messaging in chat apps or social media platforms. When a user sends a message, it's published to a topic representing a specific feed. All participants (subscribers) instantly receive the message. Comments, likes, and other interactions during the stream are published as messages, providing live chat features.
Messages don't always have text data. In streaming video apps, video and audio data are published as a stream of messages to a topic. Viewers subscribe to the topic to receive the live feed.
These are just a few examplees, as pub/sub messages and topics provide scalability and flexibility to gaming, financial apps, and more, with Redis acting as the message broker.
Using Redisson's Pub/Sub Implementations in Java Applications
The Redis Java client Redisson makes setting up distributed pub/sub with its topic implementations incredibly easy. Redisson implements three different types of topics with objects that will be familiar to Java developers. Each implementation takes care of everything on the Redis server.
Basic Topic
A basic topic can be implemented with Redisson's RTopic object. RTopic allows a Java app to subscribe to events published with multiple instances of the object with the same name.
Here's an RTopic code sample:
RTopic topic = redisson.getTopic("myTopic");
int listenerId = topic.addListener(SomeObject.class, new MessageListener() {
@Override
public void onMessage(CharSequence channel, SomeObject message) {
//...
}
});
// in other thread or JVM
RTopic topic = redisson.getTopic("myTopic");
long clientsReceivedMessage = topic.publish(new SomeObject());
Sharded Topic
Redis also supports sharded topics in cluster mode. According to the Redis documentation:
“Sharded pub/sub helps to scale the usage of Pub/Sub in cluster mode. It restricts the propagation of messages to be within the shard of a cluster. Hence, the amount of data passing through the cluster bus is limited in comparison to global pub/sub where each message propagates to each node in the cluster.”
Redisson's RShardedTopic object works much the same way as RTopic:
RShardedTopic topic = redisson.getShardedTopic("myTopic");
int listenerId = topic.addListener(SomeObject.class, new MessageListener() {
@Override
public void onMessage(CharSequence channel, SomeObject message) {
//...
}
});
// in other thread or JVM
RShardedTopic topic = redisson.getShardedTopic("myTopic");
long clientsReceivedMessage = topic.publish(new SomeObject());
Reliable Pub/Sub
Basic and sharded topics are fire-and-forget. Redis delivers each message to the subscribers connected at the moment it's published and keeps no copy, so a subscriber that is restarting or briefly disconnected never sees it. The third topic type, Reliable Pub/Sub, stores messages and tracks their delivery. Redis doesn't offer this out of the box; it's a Redisson PRO feature.
Redisson PRO implements it with the RReliablePubSubTopic object. A topic has one or more subscriptions, and each subscription keeps its own position in the topic and has its own consumers. A consumer acknowledges each message after processing it. A message that isn't acknowledged before its visibility timeout runs out is delivered again, and once it reaches its delivery limit it moves to a dead letter topic:
RReliablePubSubTopic<SomeObject> topic = redisson.getReliablePubSubTopic("anyTopic");
Subscription<SomeObject> subscription = topic.createSubscription(
SubscriptionConfig.name("anySubscription")
.deadLetterTopicName("anyTopic-dlt")
.deliveryLimit(5));
PushConsumer<SomeObject> consumer = subscription.createPushConsumer();
consumer.registerListener(MessageListenerArgs.listener((message, acknowledgment) -> {
//...
// Acknowledgment is manual by default. Until this call the message is in flight,
// and it is delivered again when its visibility timeout runs out.
acknowledgment.acknowledge(MessageAckArgs.ids(message.getId()));
}));
// in other thread or JVM
RReliablePubSubTopic<SomeObject> topic = redisson.getReliablePubSubTopic("anyTopic");
Message<SomeObject> message = topic.publish(
PublishArgs.messages(MessageArgs.payload(new SomeObject())));
Each subscription receives every message published after it was created, and the consumers of one subscription share its messages between them. Messages published while those consumers are down wait in the subscription until they come back. Reliable Pub/Sub also offers pull consumers, message grouping (messages with the same group ID are processed in order), priorities from 0 to 9, delayed delivery, deduplication, and seek, which replays a subscription from an earlier position. It runs on both Redis and Valkey. For a full walkthrough, see All about Reliable PubSub for Valkey and Redis, and for a feature-by-feature comparison with built-in pub/sub, see Reliable PubSub vs Valkey & Redis PubSub.
Redisson, the Easy Way to Use Redis Pub/Sub in Java
Pub/sub provides a loose coupling between the various components of modern application development. This messaging pattern adds asynchronous communication, scalability, and flexibility to high-performance distributed applications. As a blazing-fast message broker, Redis is the pub/sub provider of choice for developers today.
The simple objects in Redisson and Redisson PRO make it easy for Java developers to implement Redis pub/sub in their applications. With just a few lines of code, you can quickly implement basic topics, sharded topics, and, with Redisson PRO, Reliable Pub/Sub topics that acknowledge and redeliver messages. Redisson and Redisson PRO offer a number of other features, so you can seamlessly implement pub/sub with locks, queues, caches, and more.
To learn more, compare Redisson PRO vs. Community Edition.
Similar articles
- How to Search Data Stored in Redis on Java
- How to Use Redis or Valkey in Java
- How To Store JSON with Redis in Java
- How to Replace RabbitMQ With Valkey or Redis in Spring Cloud Stream Framework
- How to Use Redis Locks in Java
- Distributed Caching in Java with Valkey and Redis
- How to Use Valkey Pub/Sub (Publish/Subscribe) in Java?