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:

RedisCacheConfiguration config = RedisCacheConfiguration.defaultConfig()
    .async(true)  // Required for WebFlux
    .entryTtl(Duration.ofMinutes(10));

Without async mode, cache write operations will call .block() which throws IllegalStateException when executed on reactive threads (e.g., parallel-1, parallel-2).

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.