gpt4 book ai didi

java - 如何暂时禁用Spring缓存的缓存

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:52:51 25 4
gpt4 key购买 nike

我有一个用 @Cacheable 注释注释的 spring bean,定义如下

@Service
public class MyCacheableBeanImpl implements MyCacheableBean {
@Override
@Cacheable(value = "cachedData")
public List<Data> getData() { ... }
}

我需要此类能够禁用缓存并仅处理来自原始源的数据。这应该基于来自外部的某些事件而发生。这是我的方法:

@Service
public class MyCacheableBeanImpl implements MyCacheableBean, ApplicationListener<CacheSwitchEvent> {
//Field with public getter to use it in Cacheable condition expression
private boolean cacheEnabled = true;

@Override
@Cacheable(value = "cachedData", condition = "#root.target.cacheEnabled") //exression to check whether we want to use cache or not
public List<Data> getData() { ... }

@Override
public void onApplicationEvent(CacheSwitchEvent event) {
// Updating field from application event. Very schematically just to give you the idea
this.cacheEnabled = event.isCacheEnabled();
}

public boolean isCacheEnabled() {
return cacheEnabled;
}

}

我担心的是这种方法的“魔法”程度非常高。我什至不确定如何测试这是否可行(基于 spring 文档,这应该可行,但如何确定)。我做对了吗?如果我错了,如何改正?

最佳答案

我一直在寻找的是 NoOpCacheManager:

为了让它工作,我从 xml bean 创建切换到工厂

我做了如下事情:

    @Bean
public CacheManager cacheManager() {
final CacheManager cacheManager;
if (this.methodCacheManager != null) {
final EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
ehCacheCacheManager.setCacheManager(this.methodCacheManager);
cacheManager = ehCacheCacheManager;
} else {
cacheManager = new NoOpCacheManager();
}

return cacheManager;
}

关于java - 如何暂时禁用Spring缓存的缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com