Wou*_*ter 16 java spring spring-el spring-boot spring-cache
我正在寻找两件事:
如何使用Spring启动"dev"配置文件禁用开发期间的所有缓存.在application.properties中,没有seam作为一般设置来关闭它.什么是最简单的方法?
如何禁用特定方法的缓存?我试着像这样使用SpEl:
@Cacheable(value = "complex-calc", condition = "#{${spring.profiles.active} != 'dev'}")
public String someBigCalculation(String input){
...
}
但我可以让它发挥作用.关于SO的问题有几个问题,但它们指的是XML配置或其他东西,但我使用的是Spring Boot 1.3.3,它使用了自动配置.
我不想让事情过于复杂.
M. *_*num 39
默认情况下会自动检测和配置缓存类型.但是,您可以通过添加spring.cache.type
到配置来指定要使用的缓存类型.要禁用它,请将值设置为NONE
.
正如您想要为特定配置文件执行此操作时,将其添加到该配置文件application.properties
中,在这种情况下修改application-dev.properties
并添加
spring.cache.type=NONE
Run Code Online (Sandbox Code Playgroud)
这将禁用缓存.
在大卫·纽科姆评论道出真相:
spring.cache.type=NONE
不会关闭缓存,它可以防止缓存内容。也就是说,它仍然在程序中添加了27层AOP /拦截器堆栈,只是它没有进行缓存。这取决于他“全部关闭”的含义。
使用此选项可能会加快应用程序的启动速度,但也会带来一些开销。
1)要完全禁用Spring Cache功能
将@EnableCaching
类移动到专用的配置类中,将其包装@Profile
以启用它:
@Profile("!dev")
@EnableCaching
@Configuration
public class CachingConfiguration {}
Run Code Online (Sandbox Code Playgroud)
当然,如果您已经拥有Configuration
除dev
环境之外的所有环境都启用的类,则只需重用它即可:
@Profile("!dev")
//... any other annotation
@EnableCaching
@Configuration
public class NoDevConfiguration {}
Run Code Online (Sandbox Code Playgroud)
2)使用假的(noop)缓存管理器
在某些情况下,@EnableCaching
通过概要文件激活是不够的,因为某些类或应用程序的某些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();
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果更合适,则可以添加spring.cache.type=NONE
产生与M. Deinum答案相同的结果的属性。
如果您只有一个默认配置文件,并且不想为此创建开发和产品配置文件,我认为这可能是您项目的一个非常快速的解决方案:
将其设置在您的application.properties
:
appconfig.enablecache=true
Run Code Online (Sandbox Code Playgroud)
根据您的需要,您可以将其更改为true
/ false
。
现在,在定义 @Caching bean 时,执行以下操作:
appconfig.enablecache=true
Run Code Online (Sandbox Code Playgroud)
当属性设置为false
,NoOpCacheManager()
返回时,有效地关闭缓存。
归档时间: |
|
查看次数: |
18566 次 |
最近记录: |