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 Topic

The third topic type offered by Redisson is the reliable topic, which guarantees messages are delivered even if there are temporary network issues or service disruptions. Reliable topic is not supported by Redis out of the box, and it is only available with Redisson.

Redisson implements the RReliableTopic object for the reliable delivery of messages in the pub/sub mechanism. This object is also easy for Java developers to incorporate into their applications:

RReliableTopic topic = redisson.getReliableTopic("anyTopic");
topic.addListener(SomeObject.class, new MessageListener() {
  @Override
  public void onMessage(CharSequence channel, SomeObject message) {
    //...
  }
});

// in other thread or JVM
RReliableTopic topic = redisson.getReliableTopic("anyTopic");
long subscribersReceivedMessage = topic.publish(new SomeObject());

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 reliable topics for guaranteed message delivery. 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, visit the Redisson PRO website today. 

Similar articles