我正在尝试使用org.cache2k库创建具有自动刷新元素的缓存。例如,我定义了持续时间为5秒的元素加载器。我将过期时间设置为5秒。并且我将keepDataAfterExpired和refreshAhead选项设置为true。
第一次调用get方法大约持续5秒。没问题的。然后,我预计元素将过期,并在接下来的15秒内自动重新加载,第二个get将不会延迟地获取元素。但我的输出是:
结果
5011
结果
5000
第二个get和第一个一样持续5秒。我的目标是让元素自动刷新,并且只有第一个get会延迟。它是否可达,以及如何实现?谢谢。
static String expensiveOperation(String name) throws InterruptedException {
Thread.sleep(5000);
return "result";
}
public static void main (String... args) throws InterruptedException {
Cache<String,String> cache = new Cache2kBuilder<String, String>() {}
.expireAfterWrite(5000, TimeUnit.MILLISECONDS) // expire/refresh after 5 seconds
.keepDataAfterExpired(true)
.refreshAhead(true) // keep fresh when expiring
.loader(s->expensiveOperation(s)) // auto populating function
.build();
Instant i1 = Instant.now();
System.out.println(cache.get("a"));
Instant i2 = Instant.now();
System.out.println(Duration.between(i1,i2).toMillis());
Thread.sleep(15000);
Instant i11 = Instant.now();
System.out.println(cache.get("a"));
Instant i22 = Instant.now();
System.out.println(Duration.between(i11,i22).toMillis());发布于 2021-04-07 12:16:10
我在Cache2k中关于refreshAhead的文档中找到了答案:
刷新后,条目将处于试用期。如果在下一次到期之前无法访问该条目,则不会进行刷新,该条目将过期并将从缓存中删除。这意味着条目在试用期内停留的时间由配置的过期时间或ExpiryPolicy确定。
因此,在我的示例中,15秒足以让条目自动刷新,然后过期并删除,因此下一个get触发新的加载。
https://stackoverflow.com/questions/66890633
复制相似问题