【问题标题】:ecache store and retrieve the values from disk storageecache 存储和检索磁盘存储中的值
【发布时间】: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 配置,以及在您的两个类中,它们是如何运行的吗?两者都在同一个程序集中吗?
  • 需要更多信息 - 配置和调用时,放置后的第一个类是否能够检索它..

标签: java caching ehcache disk


【解决方案1】:

你应该注意的两件事:

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

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

    李>

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2011-12-15
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多