我目前正在使用企业版 EhCache 在我们的应用程序中实现缓存。正如所解释的here ,我通过在我的 EhCache 类中使用以下构造函数以编程方式创建两个不同的缓存实例,我用它来管理 EhCache 创建:
public class EhCache implements ICacheAccess {
private String name;
private Cache ehCache;
private CacheAttributes attrs;
public EhCache(final String name, final CacheAttributes attrs) {
this.name = name;
this.attrs = attrs;
Configuration configuration = new Configuration();
TerracottaClientConfiguration terracottaConfig
= new TerracottaClientConfiguration();
configuration.addTerracottaConfig(terracottaConfig);
final CacheConfiguration cfg = new CacheConfiguration(name, attrs.cacheSize)
.eternal(attrs.eternal).terracotta(new TerracottaConfiguration())
.timeToLiveSeconds(attrs.timeToLiveSeconds)
.timeToIdleSeconds(attrs.timeToIdleSeconds)
.statistics(attrs.statistics).overflowToOffHeap(true).maxBytesLocalOffHeap(200,MemoryUnit.MEGABYTES);
configuration.addCache(cfg);
CacheConfiguration defaultCache = new CacheConfiguration("default",
1000).eternal(false);
configuration.addDefaultCache(defaultCache);
CacheManager mgr = CacheManager.create(configuration);
ehCache = mgr.getCache(name);
LOGGER.log("ehcache is "+ehCache);
}
}
然后,我使用以下方法创建 EhCache 类的两个实例:
public void testCreateCache(String name) {
CacheAttributes attrs = new CacheAttributes();
attrs.timeToIdleSeconds = 0;
attrs.timeToLiveSeconds = 0;
Cache cache = new EhCache(name, attrs);
}
我在主方法中调用上述方法两次:
testCreateCache("cache1");
testCreateCache("cache2");
缓存1创建成功,但缓存2为空。
如果我交换创建缓存的顺序:
testCreateCache("cache2");
testCreateCache("cache1");
缓存2创建成功,但缓存1为空。
我无法理解为什么会发生这种情况。第一个缓存创建成功,但第二个缓存始终为空。
最佳答案
我认为你的问题是你调用了 CacheManager.create() 两次,因为 CacheManager 是单例。将两个缓存添加到配置对象后尝试调用它一次。
关于java - 在 Terracotta 集群上创建两个不同的缓存时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13600626/