java - Ehcache更新元素值而不改变他的timetolive

标签 java caching ehcache

我正在尝试将 Cache 中每个元素的 timeToLive 设置为 60 seconde 来做到这一点,我正在这样做:

private void putElementInCache(Cache cache, String key, Integer value) {
    Element element = new Element(key, value);
    element.setTimeToLive(60);
    cache.put(element);
}

之后我检查我的 key 是否在我的缓存中,如果它在这里我想更新值。为此,我重新使用了之前的函数,但我的元素在 60 秒后永不过期。

检查我是否在使用这段代码

while (true) {
        Element element = cache.get(key);
        Integer attempts = (Integer) element.getObjectValue() + 1;
        System.out.println("attemps : " + attempts + " and creation time is : " + element.getCreationTime() + " and expiration time is : " + element.getExpirationTime());
        putElementInCache(cache, key, attempts);
        try {
            Thread.sleep(1000); // Sleep 1 second
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }

而且我从来没有遇到过 NullPointerException。

如果我睡得比 timeToLive 长,我会得到一个 NullPointerException。

如何让我的元素在 60 秒后过期?

目标是检查 attemps 是否等于阈值,以及我是否无法从缓存中获取要放入的元素。

我的Ehcache全局配置是:

<defaultCache maxElementsInMemory="400000" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="LRU">
    <cacheEventListenerFactory
        class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
        properties="replicateAsynchronously=true, replicatePuts=false,
        replicateUpdates=false, replicateUpdatesViaCopy=false, replicateRemovals=true" />
    <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=false" />
</defaultCache>

在控制台我可以看到创建时间和过期时间一直在变化

attemps : 59 and creation time is : 1466576506096 and expiration time is : 1466576566096 attemps : 60 and creation time is : 1466576507096 and expiration time is : 1466576567096 attemps : 61 and creation time is : 1466576508096 and expiration time is : 1466576568096 attemps : 62 and creation time is : 1466576509096 and expiration time is : 1466576569096 attemps : 63 and creation time is : 1466576510097 and expiration time is : 1466576570097 attemps : 64 and creation time is : 1466576511097 and expiration time is : 1466576571097 attemps : 65 and creation time is : 1466576512097 and expiration time is : 1466576572097

最佳答案

每次将元素放入缓存时,都会将它的生存时间设置为 60 秒。 new putupdate 在该级别上没有区别。所以你总是告诉值在它被放置/更新后 60 秒过期。

根据您的描述,您的 putElementInCache 方法需要采用第四个参数,即您可以根据从缓存中检索到的前一个 Element 计算出的剩余过期时间基于 getExpirationTimenow 之间的区别。

关于java - Ehcache更新元素值而不改变他的timetolive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960291/

相关文章:

java - 在应用程序购买中工作,但方法未执行?

java - 在java中缓存sql结果集

java - 如何出于测试目的关闭 ehcache

java - 如何在Ehcache中使用SimpleCachingPageFilter更新或失效缓存?

java - 测试网络应用程序

java - "Prev"按钮未循环遍历数组,"Next"按钮工作正常

angular - 如何在 Angular 6 中使用 HttpClient get 禁用缓存

java - 带有 Spring 的 ehcache。找不到谷歌代码 xsd 文件

java - libGDX 和 Eclipse - 找不到 tools.jar

caching - 持久化/缓存 RDD 上的 Spark RDD 检查点执行 DAG 两次