EhCache кеш по умолчанию в java
У меня есть эта конфигурация для ehCache:
<ehcache>
<defaultCache
name="defaut"
maxElementsInMemory="5"
eternal="false"
timeToIdleSeconds="20"
timeToLiveSeconds="20"
overflowToDisk="false"
diskPersistent="false"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
Как получить доступ к кешу по умолчанию для EhCache?
CacheManager.getInstance().getCache("default"); // returns null
Ответы
Ответ 1
Я понимаю, что "кеш-память по умолчанию" на самом деле является шаблоном для создания новых кэшей, а не конкретным кешем.
CacheManager.getCache
будет возвращать экземпляр кэша только в том случае, если он уже создан, поэтому вам нужно будет его создать, чтобы создать новый, используя что-то вроде addCacheIfAbsent()
. Имя не имеет значения, оно будет создано по требованию с использованием настроек кэша по умолчанию.
Ответ 2
Я столкнулся с той же проблемой, пытаясь создать новый кэш.
Используя EhCache 2.7.3 Я не смог использовать метод addCacheIfAbsent(..)
поскольку он возвращает устаревший класс EhCache, а не класс Cache.
Моя первоначальная попытка была следующей:
private Cache addCache(Class<?> cacheClazz) {
CacheConfiguration cacheConfiguration = null;
{
Cache defaultCache = getCacheManager().getCache("default");
cacheConfiguration = defaultCache.getCacheConfiguration();
}
Cache newCache = new Cache(cacheConfiguration);
getCacheManager().addCache(newCache);
return newCache;
}
Но использование CacheManager.getCache("default")
возвращает null
- так что да, похоже, что нельзя получить ссылку на кэш по умолчанию (шаблон).
Я получил код, работающий следующим образом:
private Cache addCache(Class<?> cacheClazz) {
// get the default (template) cache configuration
CacheConfiguration cacheConfiguration = getCacheManager().getConfiguration().getDefaultCacheConfiguration();
// give it a unique name or the process will fail
cacheConfiguration.setName(cacheClazz.getName());
Cache newCache = new Cache(cacheConfiguration);
getCacheManager().addCache(newCache);
return newCache;
}
Это не было потокобезопасно (проверено с использованием одновременных тестов TestNg). Окончательная реализация выглядит следующим образом:
private final static Map<String, String> firstRunMap = new HashMap<>(); // Not using ConcurrentHashMap so be careful if you wanted to iterate over the Map (https://stackoverflow.com/questions/27753184/java-hashmap-add-new-entry-while-iterating)
private Cache addCache(Class<?> cacheClazz) {
final String mapKey = getMapKey(cacheClazz);
if (firstRunMap.get(mapKey) == null) {
synchronized(mapKey) {
if (firstRunMap.get(mapKey) == null) {
// -----------------------------------------------------
// First run for this cache!!!
// -----------------------------------------------------
// get the default (template) cache configuration
CacheConfiguration cacheConfiguration = getCacheManager().getConfiguration().getDefaultCacheConfiguration();
// give it a unique name or the process will fail
cacheConfiguration.setName(cacheClazz.getName());
Cache newCache = new Cache(cacheConfiguration);
getCacheManager().addCache(newCache);
// -----------------------------------------------------
// First run complete!!!
// -----------------------------------------------------
firstRunMap.put(mapKey, "");
return newCache;
}
}
}
// Not the first thread
return getCache(cacheClazz);
}
// This class is AbstractEhCache - change it to your class
private String getMapKey(Class<?> cacheClazz) {
String mapKey = AbstractEhCache.class.getName() // to differentiate from similar keys in other classes
+ "-" + cacheClazz.getName();
// Using intern() on the key as I want to synchronize on it.
// (Strings with different hashCodes represent different locks)
return mapKey.intern();
}
private Cache getCache(Class<?> cacheClazz) {
return getCacheManager().getCache(cacheClazz.getName());
}
Ответ 3
обратитесь к api ehcache
addCache
public void addCache (String cacheName)
throws IllegalStateException,
ObjectExistsException,
CacheException
Добавляет Ehcache на основе по умолчаниюCache с заданным именем.
от:
http://ehcache.org/apidocs/2.7.6/
надеюсь помочь вам!
Ответ 4
Но если мы добавим регион с именем 'default', ehcache выдаст исключение:
net.sf.ehcache.ObjectExistsException: кэш по умолчанию уже настроен