Spring Boot - 如何在开发过程中禁用@Cacheable?

Spring Boot - How to disable @Cacheable during development?

我正在寻找 2 个东西:

  1. 如何使用 Spring 引导 "dev" 配置文件在开发期间禁用所有缓存。在 application.properties 中没有接缝作为将其全部关闭的通用设置。最简单的方法是什么?

  2. 如何禁用特定方法的缓存?我试过像这样使用 SpEl:

    @Cacheable(value = "complex-calc", condition="#${spring.profiles.active} != 'dev'}")
    public String someBigCalculation(String input){
       ...
    }
    

但我可以让它工作。在 SO 上有几个与此相关的问题,但它们指的是 XML 配置或其他内容,但我使用的是 Spring Boot 1.3.3 并且它使用自动配置。

我不想让事情过于复杂。

默认情况下会自动检测和配置缓存类型。但是,您可以通过在配置中添加 spring.cache.type 来指定要使用的缓存类型。要禁用它,请将值设置为 NONE

正如你想为特定配置文件做的那样,将其添加到该配置文件 application.properties 在这种情况下修改 application-dev.properties 并添加

spring.cache.type=NONE

这将禁用缓存。

对于你的第二个问题,做这样的事情:

编写一个方法来确定特定配置文件是否处于活动状态(环境是您注入的环境)

boolean isProfileActive(String profile) { 
   return Arrays.asList(environment.getActiveProfiles()).contains(profile);
}

然后将其用于可缓存注释的拼写条件

说的是实话:

spring.cache.type=NONE doesn't switch caching off, it prevents things from being cached. i.e. it still adds 27 layers of AOP/interceptor stack to your program, it's just that it doesn't do the caching. It depends what he means by "turn it all off".

使用此选项可能会加快应用程序启动速度,但也可能会产生一些开销。

1)完全禁用 Spring 缓存功能

@EnableCaching class 移动到我们将用 @Profile 包裹的专用配置 class 中以启用它:

@Profile("!dev")
@EnableCaching
@Configuration
public class CachingConfiguration {}

当然,如果您已经为除 dev 环境之外的所有环境启用了 Configuration class,只需重复使用它即可:

@Profile("!dev")
//... any other annotation 
@EnableCaching
@Configuration
public class NoDevConfiguration {}

2) 使用假的 (noop) 缓存管理器

在某些情况下,通过配置文件激活 @EnableCaching 是不够的,因为您的某些 class 或应用程序的某些 Spring 依赖项希望从 Spring 容器一个实现 org.springframework.cache.CacheManager 接口的 bean。
在这种情况下,正确的方法是使用一个伪造的实现,它允许 Spring 解析所有依赖关系,而 CacheManager 的实现是免费的。

我们可以通过 @Bean@Profile 来实现它:

import org.springframework.cache.support.NoOpCacheManager; 

@Configuration
public class CacheManagerConfiguration {

    @Bean
    @Profile("!dev")
    public CacheManager getRealCacheManager() {
        return new CaffeineCacheManager(); 
        // or any other implementation
        // return new EhCacheCacheManager(); 
    }

    @Bean
    @Profile("dev")
    public CacheManager getNoOpCacheManager() {
        return new NoOpCacheManager();
    }
}

或者如果它更合适,您可以添加 spring.cache.type=NONE 属性 产生与 M. Deinum 答案中所写相同的结果。

如果您只有一个默认配置文件并且不想为此创建开发和生产配置文件,我认为这可能是您项目的一个非常快速的解决方案:

在您的 application.properties 中设置:

appconfig.enablecache=true

根据您的要求,您可以将其更改为true/false

现在,在定义您的@Caching bean 时,请执行以下操作:

@Bean
public CacheManager cacheManager(@Value("${appconfig.enablecache}") String enableCaching) {
    if (enableCaching.equals("true")) {
        return new EhCacheCacheManager();
        //Add your Caching Implementation here.
    }
    return new NoOpCacheManager();
}

当 属性 设置为 false 时,返回 NoOpCacheManager(),有效地关闭缓存。