Pub/Sub Messaging with Redis in Spring Boot: Real-Time Communication Made Simple
Real-time messaging is a cornerstone of modern, scalable applications. Redis Pub/Sub (Publish/Subscribe) provides a lightweight, efficient way to broadcast messages between microservices or components, enabling instant updates and decoupled communication. In this post, you'll learn how to implement a simple publish-subscribe mechanism using Redis and Spring Boot, complete with a practical example.
What is Redis Pub/Sub?
Redis Pub/Sub is a messaging pattern where publishers send messages to channels, and subscribers listen to those channels to receive messages. This allows for asynchronous, decoupled communication between different parts of your system or even different applications. Redis Pub/Sub is ideal for real-time notifications, chat, event broadcasting, and more.
When to Use Redis Pub/Sub?
- Real-time notifications (e.g., chat, alerts)
- Event broadcasting across microservices
- Loose coupling between producers and consumers
Note: Redis Pub/Sub does not provide message persistence or guaranteed delivery. For advanced messaging needs, consider message brokers like RabbitMQ or Kafka.
Implementing Redis Pub/Sub in Spring Boot
1. Add Dependencies
Add the following to your pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. Configure Redis Connection
In application.properties
:
spring.redis.host=localhost
spring.redis.port=6379
3. Define the Channel
@Bean
public ChannelTopic topic() {
return new ChannelTopic("messageChannel");
}
4. Publisher Implementation
@Service
public class RedisPublisher {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ChannelTopic topic;
public void publish(String message) {
redisTemplate.convertAndSend(topic.getTopic(), message);
}
}
5. Subscriber Implementation
@Component
public class RedisSubscriber implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("Received message: " + message.toString());
}
}
6. Configure the Listener Container
@Configuration
public class RedisConfig {
@Autowired
private RedisSubscriber redisSubscriber;
@Autowired
private ChannelTopic topic;
@Bean
public RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(redisSubscriber, topic);
return container;
}
}
7. REST Controller to Publish Messages
@RestController
public class MessageController {
@Autowired
private RedisPublisher publisher;
@GetMapping("/publish")
public String publish(@RequestParam String message) {
publisher.publish(message);
return "Message published: " + message;
}
}
How It Works
- Publisher: Sends messages to a Redis channel using
convertAndSend
. - Subscriber: Listens to the channel and processes messages in real time.
- Controller: Provides an endpoint to trigger message publishing.
When you hit /publish?message=Hello+Redis
, the message is sent to all subscribers listening on messageChannel
.
Testing the Pub/Sub Flow
- Start your Spring Boot application and ensure Redis is running.
- Open two terminal windows:
- In one, monitor the application logs to see subscriber output.
- In the other, use curl or your browser to call:
http://localhost:8080/publish?message=Hello+Redis
- The subscriber will print:
Received message: Hello Redis
Conclusion
Implementing Redis Pub/Sub in Spring Boot is straightforward and powerful for real-time messaging between services or components. With just a few configuration steps, you can enable instant, decoupled communication in your applications—perfect for microservices, notifications, or event-driven architectures.
Redis Pub/Sub keeps your system responsive, scalable, and simple to maintain.