1、pom依赖配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
2、ehcache配置文件(src/main/resources资源目录下)
<?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/ehcache"/>
<!-- 默认缓存 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<!-- 定义缓存 -->
<cache name="table1Cache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
3、ehcache配置类(@Configuration)
@Configuration
@EnableCaching // 标注启动缓存
public class CacheConfiguration {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(CacheConfiguration.class);
/**
* ehcache 主要的管理器
* @param bean
* @return
*/
@Bean
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
logger.warn("初始化EhCacheCacheManager");
return new EhCacheCacheManager(bean.getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
logger.warn("初始化EhCacheManagerFactoryBean");
EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
factoryBean.setShared(true);
return factoryBean;
}
}
4、ehcache注解使用
在service接口方法上进行缓存标注
/**
* 重工业工业增加值占比(%)历史月份
*
* @param startMonth
* @param endMonth
* @return
*/
@Cacheable(value="table1Cache") // value为已定义缓存的名字
List<JsonSetBean> indIncPercentageHistData(String startMonth, String endMonth);
5、缓存测试
测试@Cacheable标注的接口,第一次执行了Dao层查询,往后的调用没有执行Dao层,此时说明ehcache已经工作了
网友评论