【发布时间】: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
【问题讨论】: