2015-05-01 74 views
6

谷歌番石榴教程說緩存到期可以Ticker番石榴北京時間緩存過期

爲我的理解進行測試,我可以用它來強迫一個快速呼氣。 我對

但我嘗試了下面的代碼,它沒有工作,任何建議?

@Test 
public void expireAfterWriteTestWithTicker() throws InterruptedException { 
    Ticker t = new Ticker() { 
     @Override 
     public long read() { 
      return TimeUnit.MILLISECONDS.toNanos(5); 
     } 
    }; 
    //Use ticker to force expire in 5 millseconds 
    LoadingCache<String, String> cache = CacheBuilder.newBuilder() 
      .expireAfterWrite(20, TimeUnit.MINUTES).ticker(t).build(loader); 

    cache.getUnchecked("hello"); 
    assertEquals(1, cache.size()); 
    assertNotNull(cache.getIfPresent("hello")); 
    //sleep 
    Thread.sleep(10); 
    assertNull(cache.getIfPresent("hello")); //failed 

} 
+1

而不是' Thread.sleep',增加超過20分鐘的股票。例如,請參閱這些[單元測試](https://github.com/ben-manes/caffeine/blob/master/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java ) –

+0

謝謝。現在就開始工作了。 – user3644708

回答

10

只要找到我自己的答案

北京時間可用於跳過的時間,而不是過期時間

class FakeTicker extends Ticker { 

    private final AtomicLong nanos = new AtomicLong(); 

    /** Advances the ticker value by {@code time} in {@code timeUnit}. */ 
    public FakeTicker advance(long time, TimeUnit timeUnit) { 
     nanos.addAndGet(timeUnit.toNanos(time)); 
     return this; 
    } 

    @Override 
    public long read() { 
     long value = nanos.getAndAdd(0); 
     System.out.println("is called " + value); 
     return value; 
    } 
} 

@Test 
public void expireAfterWriteTestWithTicker() throws InterruptedException { 
    FakeTicker t = new FakeTicker(); 

    // Use ticker to force expire in 20 minute 
    LoadingCache<String, String> cache = CacheBuilder.newBuilder() 
      .expireAfterWrite(20, TimeUnit.MINUTES).ticker(t).build(ldr); 
    cache.getUnchecked("hello"); 
    assertEquals(1, cache.size()); 
    assertNotNull(cache.getIfPresent("hello")); 

    // add 21 minutes 
    t.advance(21, TimeUnit.MINUTES); 
    assertNull(cache.getIfPresent("hello")); 

} 
+5

'FakeTicker'類位於'com.google.common.testing' –