5

I have a Spring Boot 2 application with Redis cache. It worked just fine until I overridden CacheManager bean.

Problem: The following configuration property gets ignored (I can't turn off caching anymore):

spring.cache.type=none

Although according to the documentation it should work.

Question: How to make the spring.cache.type=none work?

There is a workaround like this, but it is far from being a good solution.

More details: Here is how my configuration looks like:

@Configuration
public class CacheConfiguration {
    @Bean
    RedisCacheWriter redisCacheWriter(RedisConnectionFactory connectionFactory) {
        return RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
    }

    @Bean
    CacheManager cacheManager(RedisCacheWriter redisCacheWriter) {
        Map<String, RedisCacheConfiguration> ttlConfiguration = ...
        RedisCacheConfiguration defaultTtlConfiguration = ...
        return new RedisCacheManager(
                redisCacheWriter, defaultTtlConfiguration, ttlConfiguration
        );
    }
}
Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148
  • With manually configuring the `CacheManager ` you disable the auto-configuration and thus the processing of the `spring.cache` annotations. If you want to use this property you will have to read and process it yourself. – M. Deinum Jun 24 '19 at 09:36

2 Answers2

6

Because you are creating the CacheManager yourself you also have to check spring.cache.type if you want to turn it of.

@Bean
@ConditionalOnExpression("${spring.cache.type} != 'none'")
CacheManager cacheManager(RedisCacheWriter redisCacheWriter) {
Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
  • 1
    I had to enclose `${spring.cache.type}` in single quotes (Using Spring 5 + Kotlin): `@ConditionalOnExpression("'${spring.cache.type}' != 'none'")` – Asa Mar 03 '20 at 22:43
1

A Built in Spring Redis Cache configuration resides in org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration

It has a @Conditional(CacheCondition.class) on it. This CacheCondition checks the value of spring.cache.type property. If its set to "NONE" the whole configuration, including the RedisCacheManager bean won't load at all.

Now as you've created your own configuration where you define the cacheManager by yourself it gets loaded regardless the value of spring.cache.type variable

So you should probably put some conditional value (that will read the spring.cache.type value or your custom condition)

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97