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

标签 spring ehcache ehcache-2

在 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/

相关文章:

java - Tapestry 组件缓存

java - Hibernate 查询缓存类型

java - 在 Spring 服务器启动期间如何使用缓存中填充的数据?

java - 当使用 token 进行身份验证时,Spring REST API Controller 将重定向到主页

Spring-Boot - 激活休眠二级缓存

java - Gemfire异常处理

java - Ehcache 2.10 线程被阻塞

java - Spring REST应用程序配置和启动

java - RestTemplate ClientHttpResponse.getBody() 抛出 I/O 错误