Spring 缓存番石榴 TTL 配置的奇怪行为
Strange Behavior for Spring cache guava TTL config
我有以下 spring 缓存配置:
spring.cache.guava.spec: expireAfterWrite=1s
那我测试一下:
@Test
public void test_not_work() {
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
expect("real method called TWO times");
// because cache should be expired after 1s
// It DOESN'T work, real method only called once
}
@Test
public void test_works() {
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
expect("real method called THREE times");
// because cache should be expired after 1s
// IT WORKS!!
}
谁能解释一下?
这是因为 Guava 无法确保在超时值到期时自动驱逐这些值。
根据其文档 here:
Caches built with CacheBuilder do not perform cleanup and evict values
"automatically," or instantly after a value expires, or anything of
the sort. Instead, it performs small amounts of maintenance during
write operations, or during occasional read operations if writes are
rare.
我有以下 spring 缓存配置:
spring.cache.guava.spec: expireAfterWrite=1s
那我测试一下:
@Test
public void test_not_work() {
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
expect("real method called TWO times");
// because cache should be expired after 1s
// It DOESN'T work, real method only called once
}
@Test
public void test_works() {
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
expect("real method called THREE times");
// because cache should be expired after 1s
// IT WORKS!!
}
谁能解释一下?
这是因为 Guava 无法确保在超时值到期时自动驱逐这些值。
根据其文档 here:
Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.