Guava Cache Hello World

大部分應用程式都會透過Cache機制,去增加效能或暫時性的備援。Guava提供了簡單的Cache實做,讓你不用替資源回收或同步問題煩惱。

我們可以透過CacheBuilder去設定Cache的條件。在build時,你可以選擇要預先提供服務實做(CacheLoader),或是在get時提供。以下是在build時,就提供了服務實做:

@Test
public void test() throws Exception {
	LoadingCache<String, String> cache =  CacheBuilder.newBuilder()
	.maximumSize(10)
	.expireAfterAccess(5, TimeUnit.SECONDS)
	.expireAfterWrite(5, TimeUnit.SECONDS)
	.softValues()
	.build(new CacheLoader<String, String>(){
		private int count = 0;
		@Override
		public String load(String key) throws Exception {
			return key + (count++);
		}
	});
 
	Assert.assertEquals("test10", cache.get("test1"));
	Thread.sleep(4000);
	Assert.assertEquals("test10", cache.get("test1"));
	Thread.sleep(2000);
	Assert.assertNull(cache.getIfPresent("test1"));
	Assert.assertEquals("test11", cache.get("test1"));
}

在get時才能決定實做:

@Test
public void testCache() throws Exception {
	Cache<String, String> cache =  CacheBuilder.newBuilder()
	.maximumSize(10)
	.expireAfterAccess(5, TimeUnit.SECONDS)
	.expireAfterWrite(5, TimeUnit.SECONDS)
	.softValues()
	.build();
 
	Assert.assertEquals("0", cache.get("test1", ()->{return "0";}));
	Thread.sleep(4000);
	Assert.assertEquals("0", cache.get("test1", ()->{return "1";}));
	Thread.sleep(2000);
	Assert.assertNull(cache.getIfPresent("test1"));
	Assert.assertEquals("2", cache.get("test1", ()->{return "2";}));
}

從範例可以得知,在cache過期前,都不會實際去執行服務取得內容。