Java tutorial
/******************************************************************************* * Copyright (c) 2005, 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package com.xyxy.platform.examples.showcase.demos.cache.guava; import static org.assertj.core.api.Assertions.*; import java.util.concurrent.TimeUnit; import com.xyxy.platform.examples.showcase.entity.User; import com.xyxy.platform.examples.showcase.service.AccountService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import com.xyxy.platform.modules.core.test.data.DataFixtures; import com.xyxy.platform.modules.core.test.log.LogbackListAppender; import com.xyxy.platform.modules.core.test.spring.SpringTransactionalTestCase; import com.xyxy.platform.modules.core.utils.Threads; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; /** * GuavaCache. * * */ @ContextConfiguration(locations = { "/applicationContext.xml" }) public class GuavaCacheDemo extends SpringTransactionalTestCase { @Autowired private AccountService accountService; @Test public void demo() throws Exception { // 1005 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/h2/cleanup-data.sql", "classpath:data/h2/import-data.sql"); // ?appenderassert LogbackListAppender appender = new LogbackListAppender(); appender.addToLogger(GuavaCacheDemo.class); // ? User user = cache.get(1L); assertThat(user.getLoginName()).isEqualTo("admin"); assertThat(appender.isEmpty()).isFalse(); appender.clearLogs(); // ? User user2 = cache.get(1L); assertThat(user2.getLoginName()).isEqualTo("admin"); assertThat(appender.isEmpty()).isTrue(); // ?? Threads.sleep(10, TimeUnit.SECONDS); User user3 = cache.get(1L); assertThat(user3.getLoginName()).isEqualTo("admin"); assertThat(appender.isEmpty()).isFalse(); } }