Java Ehcache更新元素值而不更改其timetolive

Java Ehcache更新元素值而不更改其timetolive,java,caching,ehcache,Java,Caching,Ehcache,我正在尝试将缓存中每个元素的时间间隔设置为60秒,以便这样做: private void putElementInCache(Cache cache, String key, Integer value) { Element element = new Element(key, value); element.setTimeToLive(60); cache.put(element); } 之后,我检查我的密钥是否在缓存中,如果它在这里,我想更新该值。为此,我重新使用了

我正在尝试将缓存中每个元素的时间间隔设置为60秒,以便这样做:

private void putElementInCache(Cache cache, String key, Integer value) {
    Element element = new Element(key, value);
    element.setTimeToLive(60);
    cache.put(element);
}
之后,我检查我的密钥是否在缓存中,如果它在这里,我想更新该值。为此,我重新使用了前面的函数,但我的元素在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

如果我的睡眠时间超过了生存时间,我会得到一个空点异常

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

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

我的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>

在控制台中,我可以看到创建时间和过期时间总是变化的

时间:59,创建时间:1466576096,过期时间:146657656096 时间:60,创建时间:146657607096,过期时间:14665767096 时间:61,创建时间:1466576508096,过期时间:146657658096 时间:62,创建时间:1466576509096,过期时间:146657659096 时间:63,创建时间:146657510097,过期时间:1466570097 时间:64,创建时间:146657511097,过期时间:1466571097 时间:65,创建时间:146657512097,过期时间:1466572097


每次将元素放入缓存时,都将其生存时间设置为60秒。新put和该级别的更新之间没有区别。因此,您总是告诉该值在放置/更新后60秒过期


根据您的描述,您的
putElementInCache
方法需要采用第四个参数,即剩余的过期时间,您可以根据
getExpirationTime
与现在之间的差异从缓存中检索到的上一个
元素计算剩余的过期时间。

谢谢您的回答。如果我理解它,我必须通过这样的操作来获得剩余的过期时间:
dateremainingtime=newdate().getTime()-element.getExpirationTime()
?我通过在缓存中添加一个对象作为值来实现这一点。这个对象包含创建日期和它的生命结束日期,之后我可以将现在的日期与它的生命结束日期进行比较。你有没有更新缓存项而不更改其到期日期的示例?