如何用Spring ehcache抽象动态创建缓存 [英] How to create cache dynamically with spring ehcache abstraction

查看:0
本文介绍了如何用Spring ehcache抽象动态创建缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

}

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

这篇关于如何用Spring ehcache抽象动态创建缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆