gpt4 book ai didi

spring - 如何使用 spring ehcache 抽象动态创建缓存

转载 作者:行者123 更新时间:2023-12-02 08:37:59 24 4
gpt4 key购买 nike

在 Google 代码上提供的 ehcache-spring-annotations 库中,配置选项“create-missing-caches”可用于动态创建动态缓存(未在 ehcache.xml 中定义的缓存)。纯spring ehcache抽象(Spring 3.1.1)中是否有类似的配置可用?或者有没有其他方法可以使用 spring ehcache 抽象创建动态缓存?

最佳答案

我能够通过扩展 org.springframework.cache.ehcache.EhCacheCacheManager 并重写 getCache(String name) 方法来做到这一点。下面是代码片段:

public class CustomEhCacheCacheManager extends EhCacheCacheManager {

private static final Logger logger = LoggerFactory
.getLogger(CustomEhCacheCacheManager.class);

private static final String NO_CACHE_ERROR_MSG = "loadCaches must not return an empty Collection";

@Override
public void afterPropertiesSet() {
try {
super.afterPropertiesSet();
} catch (IllegalArgumentException e) {
if (NO_CACHE_ERROR_MSG.equals(e.getMessage())) {
logger.debug("No cache was defined in ehcache.xml. The error "
+ "thrown by spring because of this was suppressed.");
} else {
throw e;
}
}
}

@Override
public Cache getCache(String name) {
Cache cache = super.getCache(name);
if (cache == null) {
logger.debug("No cache with name '"
+ name
+ "' is defined in encache.xml. Hence creating the cache dynamically...");
getCacheManager().addCache(name);
cache = new EhCacheCache(getCacheManager().getCache(name));
addCache(cache);
logger.debug("Cache with name '" + name
+ "' is created dynamically...");
}
return cache;
}

}

如果有人有其他更好的方法,请告诉我。

关于spring - 如何使用 spring ehcache 抽象动态创建缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12047759/

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