From cb23f45a77d0f8ebfa20e85269517cf395d9cf45 Mon Sep 17 00:00:00 2001 From: Calvin Date: Wed, 28 Mar 2012 01:21:47 +0800 Subject: [PATCH] =?UTF-8?q?#8=20hzl7652=E6=8F=90=E4=BA=A4=E7=9A=84GuavaCac?= =?UTF-8?q?heDemo,=E4=BD=86rebase=E5=87=BA=E9=94=99=E4=BA=86,=E5=86=8D?= =?UTF-8?q?=E6=89=8B=E5=B7=A5=E6=8F=90=E4=BA=A4=E4=B8=80=E9=81=8D=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../showcase/cache/guava/GuavaCacheDemo.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 examples/showcase/src/main/java/org/springside/examples/showcase/cache/guava/GuavaCacheDemo.java diff --git a/examples/showcase/src/main/java/org/springside/examples/showcase/cache/guava/GuavaCacheDemo.java b/examples/showcase/src/main/java/org/springside/examples/showcase/cache/guava/GuavaCacheDemo.java new file mode 100644 index 000000000..05a4512aa --- /dev/null +++ b/examples/showcase/src/main/java/org/springside/examples/showcase/cache/guava/GuavaCacheDemo.java @@ -0,0 +1,60 @@ +package org.springside.examples.showcase.cache.guava; + +import static org.junit.Assert.*; + +import java.util.concurrent.TimeUnit; + +import javax.annotation.Resource; + +import org.junit.Test; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.transaction.TransactionConfiguration; +import org.springside.examples.showcase.common.entity.User; +import org.springside.examples.showcase.common.service.AccountManager; +import org.springside.modules.test.data.H2Fixtures; +import org.springside.modules.test.spring.SpringTxTestCase; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; + +/** + * 本地缓存演示,使用GuavaCache. + * 可以通过log4jdbc查看sql情况. + * + * @author hzl7652 + */ +@ContextConfiguration(locations = { "/applicationContext.xml" }) +@TransactionConfiguration(transactionManager = "defaultTransactionManager") +public class GuavaCacheDemo extends SpringTxTestCase { + + @Resource + private AccountManager accountManager; + + @Test + public void test1() throws Exception { + H2Fixtures.reloadAllTable(dataSource, "/data/sample-data.xml"); + LoadingCache cache = CacheBuilder.newBuilder().maximumSize(100)//设置缓存个数 + .expireAfterAccess(3, TimeUnit.SECONDS)//缓存过期时间为8秒 + .build(new CacheLoader() { + + @Override + public User load(Long key) throws Exception { + return accountManager.getUser(key); + } + + }); + + User user = cache.get(1L); + assertEquals("admin", user.getLoginName());//第一次加载会查数据库 + + User user2 = cache.get(1L);//第二次加载时直接从缓存里取 + assertEquals("admin", user2.getLoginName()); + + Thread.sleep(10000); + user = cache.get(1L); + ;//第三次加载时,因为缓存已经过期所以会查数据库 + System.out.println(user); + assertEquals("admin", user.getLoginName()); + } +}