差異處
這裏顯示兩個版本的差異處。
java:guava:cache:helloworld [2016/04/13 23:30] tony |
java:guava:cache:helloworld [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>java guava}} | ||
- | ====== Guava Cache Hello World ====== | ||
- | ===== Introduction ===== | ||
- | 大部分應用程式都會透過Cache機制,去增加效能或暫時性的備援。Guava提供了簡單的Cache實做,讓你不用替資源回收或同步問題煩惱。 | ||
- | ===== How to? ===== | ||
- | 我們可以透過CacheBuilder去設定Cache的條件。在build時,你可以選擇要預先提供服務實做,或是在get時提供: | ||
- | <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~~ |