如何用Spring ehcache抽象动态创建缓存

人气:57 发布:2023-01-03 标签: spring ehcache ehcache-2

问题描述

在Google代码中可用的ehcache-Spring-Annotation库中,有一个配置选项"create-Missing-caches"可用于动态创建动态缓存(未在ehcache.xml中定义的缓存)。纯Spring ehcache抽象(Spring3.1.1)中是否有类似的配置?或者,有没有其他方法可以使用Spring ehcache抽象创建动态缓存?

GetCache

我可以通过扩展org.springframework.cache.ehcache.EhCacheCacheManager和覆盖推荐答案(字符串名)方法来实现。以下是代码片段:

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;
}

}

如果有人有其他更好的方法,请让我知道。

20