2012-12-07 50 views
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))); 
    } 
} 

也就是說,始終關閉緩存導致緩存未命中。

雖然測試失敗。我的解釋不正確?

+1

你爲什麼要使用'從(「MAXIMUMSIZE = 0」)'而不是'.maximumSize(0) '?當你從某些屬性/設置(例如命令行,文件等等)獲取緩存配置時,將使用'from(String spec)'方法。當以這種方式編程配置配置時應該使用實際的方法。 – ColinD

+0

謝謝,科林。這就是爲了這個單元測試例子的目的而完成的 - 真實組件獲取彈簧注入的緩存規格作爲道具 – jorgetown

回答

4

方法newBuilder使用默認設置構造一個新的CacheBuilder實例,忽略對from的調用。但是,您想要構建具有特定最大大小的CacheBuilder。所以,請取消撥打電話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(); 
        } 
       }); 
+0

DOH。現貨,謝謝! – jorgetown