我在尝试创建新缓存时遇到了同样的问题。
使用EhCache 2.7.3,我无法使用该方法,因为它返回已弃用的EhCache类,而不是Cache类。addCacheIfAbsent(..)
我最初的尝试如下:
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());
}