我在寻找2个问题。
如何在Spring Boot "dev "配置文件的开发过程中禁用所有缓存。在application.properties中似乎没有一个通用的设置来关闭所有缓存。最简单的方法是什么?
如何禁止一个特定方法的缓存?我试着用SpEl这样做。
@Cacheable(value = "complex-calc", condition="#${spring.profiles.active} != 'dev'}")
public String someBigCalculation(String input){
...
}
但我可以让它工作。SO上有几个问题与此有关,但他们提到了XML配置或其他东西,但我使用的是Spring Boot 1.3.3,这使用了自动配置。
我不想把事情搞得太复杂。
在 David Newcomb评论 说的是事实。
spring.cache.type=NONE
并不是把缓存关掉,而是防止东西被缓存,也就是说,它还是会给你的程序增加27层AOPinterceptor栈,只是它不做缓存。这要看他说的 "全部关闭 "是什么意思。
使用这个选项可能会加快应用程序的启动速度,但也可能会有一些开销。
1)要完全关闭Spring Cache功能。
移动 @EnableCaching
类中的一个专门的配置类,我们将用一个 @Profile
启用它。
@Profile("!dev")
@EnableCaching
@Configuration
public class CachingConfiguration {}
当然,如果你已经有一个 Configuration
类,除了 dev
环境,重用即可。
@Profile("!dev")
//... any other annotation
@EnableCaching
@Configuration
public class NoDevConfiguration {}
2) 使用一个假的(noop)Cache管理器
在某些情况下,激活 @EnableCaching
因为你的一些类或你的应用程序的一些Spring依赖关系希望从Spring容器中获取一个实现Spring容器的Bean。org.springframework.cache.CacheManager
接口。在这种情况下,正确的方法是使用一个假的实现,让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答案中写入的结果相同。
缓存的类型默认是自动检测和配置的。但是,您可以通过添加以下信息来指定使用哪种缓存类型 spring.cache.type
到您的配置中。要禁用它,请将值设置为 NONE
.
当你想对一个特定的配置文件进行添加时,将其添加到该配置文件中 application.properties
在这种情况下,修改 application-dev.properties
并加
spring.cache.type=NONE
这将禁用缓存。
对于你的第二个问题,可以这样做。
写一个方法来确定一个特定的配置文件是否处于活动状态(环境就是你注入的环境)。
boolean isProfileActive(String profile) {
return Arrays.asList(environment.getActiveProfiles()).contains(profile);
}
然后在可缓存注解的spel条件中使用该条件。