With Spring Boot 2.1 I am defining a RedisCacheManager bean in a configuration file, with Java configuration. Everything works correctly but I would like sometimes to disable it, for instance in the tests. Spring Boot provides the spring.cache.type=NONE
to disable caching, as per this documentation. However, this property will not work because I already define a CacheManager, and as such Spring Boot will not configure the NoOpCacheManager I would like there (there is a @ConditionalOnMissingBean(CacheManager.class)
on the NoOpCacheConfiguration
which has lower precedence than RedisCacheConfiguration
).
When defining caches, whatever the provider (for intance Caffeine), we usually define them as beans, which are afterwards resolved by Spring Boot's auto-configuration into a SimpleCacheManager
.
For instance
@Bean
public Cache myCache() {
return new CaffeineCache(
"my-cache",
Caffeine.newBuilder()
.maximumSize(10)
.build());
}
Unfortunately this is not possible with Redis, because its Cache
implementation, RedisCache
, is not public.
Another thing we like to do is to define a bean CacheManagerCustomizer<?>
, for instance with Caffeine
@Bean
public CacheManagerCustomizer<CaffeineCacheManager> caffeineCacheManager() {
return cacheManager -> cacheManager
.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES));
}
Again this is not possible with Redis, as RedisCacheManager
is immutable.
So the only solution right now is to create our own RedisCacheManager, but this prevent the usage of spring.cache.type: NONE
.
So here is my question. What is the best way to configure a Redis cache with Spring Boot so that we can disable it as needed ?
Bean
that you don't need in test profile with@Profile("!test")
– Hartsell