【问题标题】:Ehcache update element value without changing his timetoliveEhcache 更新元素值而不改变他的生存时间
【发布时间】:2016-10-23 22:31:32
【问题描述】:

我正在尝试将缓存中每个元素的 à timeToLive 设置为 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。

如果我的睡眠时间大于 timeToLive,我会收到 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,创建时间为:1466576506096,过期时间为:1466576566096 尝试次数:60,创建时间为:1466576507096,到期时间为:1466576567096 尝试次数:61,创建时间为:1466576508096,到期时间为:1466576568096 尝试次数:62,创建时间为:1466576509096,到期时间为:1466576569096 尝试次数:63,创建时间为:1466576510097,到期时间为:1466576570097 尝试次数:64,创建时间为:1466576511097,到期时间为:1466576571097 尝试次数:65,创建时间:1466576512097,过期时间:1466576572097

【问题讨论】:

    标签: java caching ehcache


    【解决方案1】:

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

    根据您的描述,您的 putElementInCache 方法需要采用第四个参数,这是您可以根据之前的 Element 根据 getExpirationTime 和 现在。

    【讨论】:

    • 感谢您的回答。如果我理解它,我必须通过执行以下操作来获得剩余的到期时间:Date remainingTime = new Date().getTime() - element.getExpirationTime()?我通过在缓存中添加一个对象作为值来做到这一点。这个对象包含创建日期和它的生命结束日期,之后我可以将现在的日期与它生命结束的日期进行比较。
    • 您有没有更新缓存项而不更改其过期时间的示例?
    猜你喜欢
    • 2014-05-30
    • 1970-01-01
    • 2023-03-15
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多