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

4
在Google Code上可用的ehcache-spring-annotations库中,有一个“create-missing-caches”的配置选项可用于在运行时创建动态缓存(缓存未在ehcache.xml中定义)。在纯Spring ehcache抽象(Spring 3.1.1)中是否有类似的配置可用?或者是否有其他方法可以使用Spring ehcache抽象来创建动态缓存?
1个回答

11

我通过扩展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;
}

}

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


1
如果您不关心日志记录,getCache()方法可以更简单地编写为: getCacheManager().addCacheIfAbsent(name); return super.getCache(name); - engfer
getCacheManager().cacheExists(name) 返回 true,即使该缓存名称不存在。 - user1569858

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接