gpt4 book ai didi

java - ehcache 持续存在磁盘问题

转载 作者:IT老高 更新时间:2023-10-28 21:19:20 25 4
gpt4 key购买 nike

我想用 Java 中的 ehcache 做一些我认为应该非常简单的事情,但是我已经花了足够多的时间让自己对文档感到沮丧......

  1. 将值写入磁盘持久缓存。关机。

  2. 重新启动并读取该值。

这是我的 Java 函数:

private static void testCacheWrite() {

// create the cache manager from our configuration
URL url = TestBed.class.getClass().getResource("/resource/ehcache.xml");
CacheManager manager = CacheManager.create(url);
// check to see if our cache exits, if it doesn't create it
Cache testCache = null;
if (!manager.cacheExists("test")) {
System.out.println("No cache found. Creating cache...");
int maxElements = 50000;
testCache = new Cache("test", maxElements,
MemoryStoreEvictionPolicy.LFU, true, null, true, 60, 30,
true, Cache.DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS, null);
manager.addCache(testCache);
// add an element to persist
Element el = new Element("key", "value");
testCache.put(el);
testCache.flush();
System.out.println("Cache to disk. Cache size on disk: " +
testCache.getDiskStoreSize());
} else {
// cache exists so load it
testCache = manager.getCache("test");
Element el = testCache.get("key");
if (null == el) {
System.out.print("Value was null");
return;
}
String value = (String) el.getObjectValue();
System.out.println("Value is: " + value);
}
manager.shutdown();
}

这是我的缓存配置(ehcache.xml):

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="C:/mycache"/><!-- java.io.tmpdir -->
<defaultCache
maxElementsInMemory="10000"
eternal="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
</ehcache>

尽管我在第一次运行后在磁盘上看到了 test.index 和 test.data 文件,但此函数的输出始终如下(它似乎从未从磁盘加载缓存):

No cache found. Creating cache...
Cache to disk. Cache size on disk: 2

我一定是在做一些蠢事,但我不确定是什么!

最佳答案

好的,我解决这个问题的方法是使用配置文件配置我的缓存。这是更新的配置:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

<diskStore path="C:/mycache" />

<defaultCache
maxElementsInMemory="10000"
eternal="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />

<cache
name="test"
maxElementsInMemory="500"
eternal="true"
overflowToDisk="true"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="1"
memoryStoreEvictionPolicy="LFU" />

</ehcache>

所以基本上我没有使用构造函数来定义缓存。

我想这会起作用,但我仍然想知道为什么以编程方式定义的缓存不能保存在磁盘上(尤其是因为它们仍然写入磁盘!)。

感谢大家的评论。

关于java - ehcache 持续存在磁盘问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1729605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com