WebFlux and Reactive Support
Redis Cache Java fully supports Spring WebFlux and reactive programming with Project Reactor.
Overview
As of Spring Framework 6.1+, the @Cacheable annotation automatically adapts to reactive return types like Mono<T> and Flux<T>:
-
The emitted value (not the Mono/Flux itself) is cached
-
Cache hits return the cached value wrapped in a Mono/Flux
-
Caching happens after the reactive stream completes
-
Errors are not cached
Configuration
|
When using Redis Cache Java with Spring WebFlux, you must enable async mode to avoid blocking operations on reactive threads:
Without async mode, cache write operations will call |
Example
Service with Reactive Caching
@Service
public class PersonService {
@Cacheable("persons")
public Mono<Person> findPerson(String id) {
// Reactive data loading
return webClient.get()
.uri("/persons/{id}", id)
.retrieve()
.bodyToMono(Person.class);
}
}
Configuration
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager(RedisClient redisClient) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultConfig()
.async(true) // Enable async mode for WebFlux
.entryTtl(Duration.ofMinutes(10))
.redisType(RedisType.JSON);
return RedisCacheManager.builder(redisClient)
.defaults(config)
.build();
}
}
Additional Resources
For complete working examples, see the WebFlux integration tests.