ecache存储并从磁盘存储中检索值

时间:2015-08-14 11:36:13

标签: java caching ehcache disk

我正在使用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...!!");
}

1 个答案:

答案 0 :(得分:0)

你应该注意两件事:

  1. CacheManager.getInstance()CacheManager.newInstance()不相同。第一个将使用默认配置创建缓存管理器,并将其关联为 singleton 缓存管理器。第二个不会做这个协会。它可能不会影响您,但这可能很重要,具体取决于设置。

  2. 您的示例代码会关闭缓存管理器,这意味着除非两位代码同时运行,否则它们将永远不会看到相同的CacheManagerCache或数据。

  3. 建议您在一个位置创建和关闭缓存管理器 - 如ServletContextListener - 使用允许您指定要加载的确切配置文件的方法之一。

    然后只需在需要使用它的代码中使用CacheManager.getCacheManager(String name)访问它。

    注意:您可能需要编辑问题以指明运行示例代码的输出内容。这可能会影响这个答案。

相关问题