【问题标题】:Spring Boot: Overriding CacheManager bean makes cache related properties not workSpring Boot:覆盖 CacheManager bean 使缓存相关属性不起作用
【发布时间】:2019-11-06 01:36:17
【问题描述】:

我有一个带有 Redis 缓存的 Spring Boot 2 应用程序。在我覆盖 CacheManager bean 之前,它工作得很好。

问题:以下配置属性被忽略(我无法再关闭缓存):

spring.cache.type=none

虽然according to the documentation 应该可以工作。

问题:如何使spring.cache.type=none 工作?

有一个解决方法like this,但这远不是一个好的解决方案。

更多细节:我的配置如下所示:

@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
        );
    }
}

【问题讨论】:

  • 通过手动配置CacheManager ,您将禁用自动配置,从而禁用spring.cache 注释的处理。如果你想使用这个属性,你必须自己阅读和处理它。

标签: java spring spring-boot redis spring-cache


【解决方案1】:

因为您是自己创建 CacheManager,所以如果您想关闭它,还必须检查 spring.cache.type

@Bean
@ConditionalOnExpression("${spring.cache.type} != 'none'")
CacheManager cacheManager(RedisCacheWriter redisCacheWriter) {

【讨论】:

  • 我必须将 ${spring.cache.type} 括在单引号中(使用 Spring 5 + Kotlin):@ConditionalOnExpression("'${spring.cache.type}' != 'none'")
【解决方案2】:

一个内置的 Spring Redis 缓存配置驻留在org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration

上面有一个@Conditional(CacheCondition.class)。 这个CacheCondition 检查spring.cache.type 属性的值。如果将其设置为“NONE”,则整个配置,包括 RedisCacheManager bean 将根本不会加载。

现在,当您创建自己的配置时,您可以自己定义cacheManager,无论spring.cache.type 变量的值如何,它都会被加载

所以您可能应该输入一些条件值(将读取 spring.cache.type 值或您的自定义条件)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2019-03-20
    • 2020-06-22
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多