差異處
這裏顯示兩個版本的差異處。
java:guava:cache:helloworld [2016/04/13 14:43] tony |
java:guava:cache:helloworld [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>java guava}} | ||
- | ====== Guava Cache Hello World ====== | ||
- | ===== How to? ===== | ||
- | <code java> | ||
- | 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")); | ||
- | } | ||
- | } | ||
- | </code> | ||
- | ===== ===== | ||
- | ---- | ||
- | \\ | ||
- | ~~DISQUS~~ |