Как динамически создавать кеш с помощью абстракции Spring ehcache

В библиотеке ehcache-spring-annotations, доступной в коде Google, доступен параметр конфигурации «create-missing-caches» для создания динамических кешей (кеш, не определенный в ehcache.xml) «на лету». Доступна ли аналогичная конфигурация в чистой абстракции Spring ehcache (Spring 3.1.1)? Или есть ли другой способ создавать динамические кеши, используя абстракцию Spring ehcache?


person Sudhir    schedule 21.08.2012    source источник


Ответы (1)


Я смог сделать это, расширив 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;
}

}

Если у кого-то есть другой лучший подход, пожалуйста, дайте мне знать.

person Sudhir    schedule 21.08.2012
comment
Если вас не волнует ведение журнала, метод getCache() можно записать проще: getCacheManager().addCacheIfAbsent(name); return super.getCache(name); - person engfer; 11.02.2014
comment
getCacheManager().cacheExists(name) возвращает значение true, даже если это имя кеша не существует. - person ; 29.01.2015