【发布时间】:2015-11-07 15:40:48
【问题描述】:
我正在使用 ehcache 来满足我的一项要求。它必须将一些键值对存储到磁盘存储中,并使用多个请求从 Web 服务器多次检索。
但是在尝试使用同一缓存从另一个实例检索时出现空指针异常。
配置ehcache.xml:
<diskStore path="java.io.tmpdir"/>
<cache name="cache1"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300"
timeToLiveSeconds="6000"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap" />
</cache>
请任何人帮助正确地做到这一点。
示例代码:
//1. Create a cache manager
CacheManager cm = CacheManager.newInstance();
//cm.addCache("cache1");
//2. Get a cache called "cache1", declared in ehcache.xml
Cache cache = cm.getCache("cache1");
//3. Put few elements in cache
for(int i=0; i<=100; i++){
cache.put(new Element("key"+i,"cache"+i));
}
//4. Get element from cache
Element ele = cache.get("key2");
//5. Print out the element
String output = (ele == null ? null : ele.getObjectValue().toString());
System.out.println(output);
//6. Is key in cache?
System.out.println(cache.isKeyInCache("key3"));
System.out.println(cache.isKeyInCache("key101"));
//7. shut down the cache manager
cm.shutdown();
另一个从缓存中检索的类:
CacheManager cm = CacheManager.getInstance();
if(cm.cacheExists("cache1")){
System.out.println("chache is working...!!");
Cache cache = cm.getCache("cache1");
Element ele = cache.get("2");
Serializable value = ele.getValue();
System.out.println(value.toString());
} else {
System.out.println("chache is not working...!!");
}
【问题讨论】:
-
我猜当您检索时,您错过了在键中添加“键”文字。元素ele=cache.get("key2");
-
很抱歉,实际上我错过了密钥,但即使我放了密钥,我也无法检索该值。 System.out.println(cache.getDiskStoreSize());对于上面的代码我得到“101”我做了同样的检索代码输出是“0”
-
您能详细解释一下您的 ehcache 配置,以及在您的两个类中,它们是如何运行的吗?两者都在同一个程序集中吗?
-
需要更多信息 - 配置和调用时,放置后的第一个类是否能够检索它..