這是本文件的舊版!
Guava Cache Hello World
How to?
package org.tonylin.practice.guava.cache; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; public class TestCache { @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";})); } @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")); } }