Mastering Redis Pub/Sub in Spring Boot: Step‑by‑Step Guide
This tutorial explains the Redis publish/subscribe pattern, contrasts it with the observer pattern, and provides a complete Spring Boot example—including configuration, publisher and subscriber code, and verification steps—to help developers quickly implement real‑time messaging with Redis.
In the previous tutorial we covered Redis as a high‑performance key/value cache; now we explore other powerful Redis features, starting with the publish/subscribe (Pub/Sub) pattern.
Publish/Subscribe Pattern
The pattern involves two roles: a Publisher that produces messages and a Subscriber that consumes them. It is a form of the producer‑consumer model widely used in system design, such as configuration centers that push updates to subscribed services.
What is the Publish/Subscribe pattern?
Publishers and Subscribers interact indirectly; a middle component (the broker) forwards messages, enabling loose coupling and allowing producers to operate at full speed regardless of consumer processing rates.
Is it the same as the Observer pattern?
Although the roles look similar to Subject and Observer, the key difference lies in the architecture: Pub/Sub introduces an intermediate broker, whereas the Observer pattern connects subjects directly to observers.
Key distinction
The broker acts like a buffer, decoupling publishers from subscribers and providing a "peak‑shaving" effect. Middleware such as RabbitMQ, Kafka, and RocketMQ implement this buffering, and Redis also offers a simple Pub/Sub implementation for lightweight scenarios.
Hands‑On Exercise
We will build a Spring Boot application that publishes messages via a REST endpoint and subscribes to them, printing received messages to the console.
Step 1 – Create a basic Spring Boot project
(If you need guidance, refer to a Spring Boot starter tutorial.)
Step 2 – Add required dependencies to pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>Step 3 – Create a REST controller to publish messages
@SpringBootApplication
public class Chapter55Application {
private static final String CHANNEL = "didispace";
public static void main(String[] args) {
SpringApplication.run(Chapter55Application.class, args);
}
@RestController
static class RedisController {
private final RedisTemplate<String, String> redisTemplate;
public RedisController(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@GetMapping("/publish")
public void publish(@RequestParam String message) {
// Send message
redisTemplate.convertAndSend(CHANNEL, message);
}
}
}Step 4 – Implement a subscriber to handle incoming messages
@Slf4j
@Service
static class MessageSubscriber {
public MessageSubscriber(RedisTemplate<String, String> redisTemplate) {
RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
redisConnection.subscribe(new MessageListener() {
@Override
public void onMessage(Message message, byte[] pattern) {
// Process received message
log.info("Receive message : " + message);
}
}, CHANNEL.getBytes(StandardCharsets.UTF_8));
}
}Step 5 – Verify the setup
Run the Spring Boot application.
Invoke the endpoint, e.g., curl localhost:8080/publish?message=hello.
Check the console; you should see the logged message.
2021-06-19 16:22:30.935 INFO 34351 --- [ioEventLoop-4-2] c.Chapter55Application$MessageSubscriber : Receive message : helloThe tutorial ends here. The full project source is available in the chapter5-5 directory of the Spring Boot Learning repository.
GitHub: https://github.com/dyc87112/SpringBoot-Learning/
Gitee: https://gitee.com/didispace/SpringBoot-Learning/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
