如何禁用Guava缓存?

jor*_*own 3 java guava

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)));
    }
}
Run Code Online (Sandbox Code Playgroud)

也就是说,关闭缓存总是会导致缓存未命中.

但测试失败了.我的解释不正确吗?

rep*_*mer 6

该方法使用默认设置newBuilder构造一个新CacheBuilder实例,忽略对该调用from.但是,您希望构造CacheBuilder具有特定最大大小的a.所以,删除对的呼叫newBuider.您应该使用您的调用来build获得CacheBuilder与您的规范匹配,而不是使用默认设置:

underTest = CacheBuilder.from("maximumSize=0")
                .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();
                    }
                });
Run Code Online (Sandbox Code Playgroud)