1.pom.xml配置 引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
2.编写配置类,设置缓存机制
@Configuration
@EnableCaching
public class CacheConfiguration {
@Bean
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean) {
return new EhCacheCacheManager(bean.getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("config/ehcache.xml"));
cacheManagerFactoryBean.setShared(true);
return cacheManagerFactoryBean;
}
}
3.ehcache.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir/Tmp_EhCache" />
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />
<cache name="snailAuthCache" eternal="false" maxElementsInMemory="10000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="0" memoryStoreEvictionPolicy="LFU" />
</ehcache>
4.测试
a.编写service方法
@Service
public class AuthServiceImpl implements IAuthService {
@Cacheable(value = "snailAuthCache", key = "#userNo")
@Override
public SecurityUserDetails getUserDetlByUserNo(String userNo) {
System.out.println("开始查询.....");
try {
Thread.sleep(5 * 1000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("查询结束......");
return new SecurityUserDetails();
}
}
这里例子只用到了@Cacheable注解,还有@CachePut,@CacheEvict大伙可以自己加上做个测试,我这里就不列出来了
用法如下图
b.编写control
@RestController
public class HahaCtr {
@Autowired
private IAuthService authService;
@RequestMapping("/haha")
public String haha() {
Long startTime = System.currentTimeMillis();
authService.getUserDetlByUserNo("test");
System.out.println("耗时:" + (System.currentTimeMillis() - startTime));
return "this is a test request";
}
}
c.测试结果
第一次请求到”…/haha”请求时,控制台会输出:
开始查询.....
查询结束......
耗时:5000
再次请求到”…/haha”请求时,控制台会输出:
耗时:0
本文暂时没有评论,来添加一个吧(●'◡'●)