首页>代码>springside的showcase>/showcase/src/main/java/org/springside/examples/showcase/demos/cache/guava/GuavaCacheDemo.java
package org.springside.examples.showcase.demos.cache.guava; import static org.junit.Assert.*; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springside.examples.showcase.entity.User; import org.springside.examples.showcase.service.AccountService; import org.springside.modules.test.data.DataFixtures; import org.springside.modules.test.log.Log4jMockAppender; import org.springside.modules.test.spring.SpringTransactionalTestCase; import org.springside.modules.utils.Threads; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; /** * 本地缓存演示,使用GuavaCache. * * @author hzl7652 */ @ContextConfiguration(locations = { "/applicationContext.xml" }) public class GuavaCacheDemo extends SpringTransactionalTestCase { private static Logger logger = LoggerFactory.getLogger(GuavaCacheDemo.class); @Autowired private AccountService accountService; @Test public void demo() throws Exception { ////设置缓存最大个数为100,缓存过期时间为5秒 LoadingCache<Long, User> cache = CacheBuilder.newBuilder().maximumSize(100) .expireAfterAccess(5, TimeUnit.SECONDS).build(new CacheLoader<Long, User>() { @Override public User load(Long key) throws Exception { logger.info("fetch from database"); return accountService.getUser(key); } }); //初始化数据 DataFixtures.executeScript(dataSource, "classpath:data/cleanup-data.sql", "classpath:data/import-data.sql"); //插入appender用于assert。 Log4jMockAppender appender = new Log4jMockAppender(); appender.addToLogger(GuavaCacheDemo.class); //第一次加载会查数据库 User user = cache.get(1L); assertEquals("admin", user.getLoginName()); assertFalse(appender.isEmpty()); appender.clearLogs(); //第二次加载时直接从缓存里取 User user2 = cache.get(1L); assertEquals("admin", user2.getLoginName()); assertTrue(appender.isEmpty()); //第三次加载时,因为缓存已经过期所以会查数据库 Threads.sleep(10, TimeUnit.SECONDS); User user3 = cache.get(1L); assertEquals("admin", user3.getLoginName()); assertFalse(appender.isEmpty()); } }
最近下载更多
bannerwang LV2
2018年10月30日
wkc LV21
2018年5月13日
dachoumomo LV12
2018年2月2日
yhlcrl LV1
2016年3月10日
微微上翘 LV23
2015年11月30日
zzlsrj LV10
2015年3月14日
骑着猪猪去逛街 LV32
2013年12月27日
pauldu1104 LV1
2013年7月14日
jaodge LV1
2013年6月24日
cxw LV1
2013年5月15日
最近浏览更多
酒瓯224656565
2019年10月14日
暂无贡献等级
shuiyizq LV5
2019年7月30日
chengqiang LV13
2019年5月28日
bannerwang LV2
2018年10月30日
wkc LV21
2018年5月13日
dachoumomo LV12
2018年2月2日
zyl LV34
2017年10月23日
sdomysky1234 LV6
2017年2月28日
xianggang LV1
2017年1月8日
danelumax
2016年12月20日
暂无贡献等级