2
JavaCachingWithGuava建議關閉緩存的規範方法是設置maximumSize = 0。 不過,我期望下測試通過:如何禁用番石榴緩存?
public class LoadingCacheTest {
private static final Logger LOG = LoggerFactory.getLogger(LoadingCacheTest.class);
LoadingCache<String, Long> underTest;
@Before
public void setup() throws Exception {
underTest = CacheBuilder.from("maximumSize=0").newBuilder()
.recordStats()
.removalListener(new RemovalListener<String, Long>() {
@Override
public void onRemoval(RemovalNotification<String, Long> removalNotification) {
LOG.info(String.format("%s cached value %s for key %s is evicted.", removalNotification.getCause().name(), removalNotification.getValue(), removalNotification.getKey()));
}
})
.build(new CacheLoader<String, Long>() {
private final AtomicLong al = new AtomicLong(0);
@Override
public Long load(@NotNull final String key) throws Exception {
LOG.info(String.format("Cache miss for key '%s'.", key));
return al.incrementAndGet();
}
});
}
@Test
public void testAlwaysCacheMissIfCacheDisabled() throws Exception {
String key1 = "Key1";
String key2 = "Key2";
underTest.get(key1);
underTest.get(key1);
underTest.get(key2);
underTest.get(key2);
LOG.info(underTest.stats().toString());
Assert.assertThat(underTest.stats().missCount(), is(equalTo(4L)));
}
}
也就是說,始終關閉緩存導致緩存未命中。
雖然測試失敗。我的解釋不正確?
你爲什麼要使用'從(「MAXIMUMSIZE = 0」)'而不是'.maximumSize(0) '?當你從某些屬性/設置(例如命令行,文件等等)獲取緩存配置時,將使用'from(String spec)'方法。當以這種方式編程配置配置時應該使用實際的方法。 – ColinD
謝謝,科林。這就是爲了這個單元測試例子的目的而完成的 - 真實組件獲取彈簧注入的緩存規格作爲道具 – jorgetown