Spring Boot’s New @RedisListener Annotation for Elegant Message Listening
This article introduces Spring Boot 4.1.0’s @RedisListener annotation, showing how it simplifies Redis Pub/Sub integration by eliminating boilerplate, supporting multiple topics, custom converters, and validation, with step‑by‑step code examples and CLI demonstrations.
Environment: Spring Boot 4.1.0.
1. Introduction
Redis is known for fast in‑memory caching, and its Pub/Sub feature is powerful for low‑latency real‑time messaging. Upgrading to Spring Boot 4 cleans up the code for configuring message listeners and containers, removing much boilerplate.
What is Pub/Sub?
In short, an application subscribes to a topic; when an event is published to that topic, it is delivered to all subscribers.
2. Practical Example
2.1 Prepare the environment
Add the Spring Data Redis starter dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>Configure Redis connection in application.yml:
spring:
data:
redis:
client-type: lettuce
host: localhost
port: 6379
password: xxxooo
lettuce:
pool:
max-wait: -1
max-active: 8
max-idle: 8
min-idle: 82.2 Basic usage
Define a component and annotate a method with @RedisListener:
@Component
public class MyService {
@RedisListener(topic = "my-channel")
public void processOrder(String data) { ... }
}The framework automatically creates a listener for the method and invokes it whenever a message arrives on my-channel. The listener is registered in the RedisMessageListenerContainer and can be located via the RedisListenerEndpointRegistry bean.
Multiple topics can be bound to the same method by repeating the annotation:
@Component
public class MyService {
@RedisListener(topic = "my-channel-1")
@RedisListener(topic = "my-channel-2")
public void processOrder(String data) {
System.err.println("Received message: %s".formatted(data));
}
}Publish messages with the Redis CLI:
127.0.0.1:6379> publish my-channel-1 China
(integer) 1
127.0.0.1:6379> publish my-channel-2 Hello China
(integer) 1Console output shows the two messages being processed.
2.3 Method parameter formats
The listener method can accept various parameter types. For example, to receive a deserialized Order object together with the matched topic pattern:
@RedisListener("order-channels*")
public void processOrder(Order order, @Header("pattern") Topic pattern) {
System.err.println("Order: %s, Topic: %s".formatted(order, pattern.getTopic()));
}Publishing a JSON payload:
127.0.0.1:6379> publish order-channels-create '{"sno":"S-000001","amount":66.66,"address":"CN"}'
(integer) 1Produces console output with the deserialized order and the topic.
Supported parameter types include: org.springframework.messaging.Message – the raw Redis message with headers.
Parameters annotated with @Header – extract a specific header such as pattern.
Parameters annotated with @Headers – receive all headers as a Map.
Unannotated parameters – treated as the payload; can be marked with @Payload and optionally validated with @Valid.
2.4 Custom message conversion
The default conversion is handled by DefaultMessageHandlerMethodFactory. To add custom converters, implement RedisListenerConfigurer:
@Configuration
public class AppConfig implements RedisListenerConfigurer {
@Override
public void configureMessageConverters(RedisMessageConverters.Builder builder) {
builder.withStringConverter(StandardCharsets.UTF_8)
.addCustomConverter(new JdkSerializationRedisSerializer());
}
}Out‑of‑the‑box converters include StringMessageConverter, ByteArrayMessageConverter, and a JSON converter that activates when a supported library (Jackson, Gson, etc.) is on the classpath.
2.5 Message validation
Apply @Valid to a payload object to trigger bean‑validation. Example Order record:
public record Order(
String sno,
BigDecimal amount,
@NotEmpty(message = "Order address cannot be empty") String address) {}Use the validated object in the listener:
@Component
@Validated
public class MyService {
@RedisListener("order-channels*")
public void processOrder(@Valid Order order) {
System.err.println("Order content: %s".formatted(order));
}
}Note that the class must be annotated with @Validated for validation to take effect.
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.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
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.
