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