1.springboot 整合 ehcache
1.1 引入pom依赖
<!-- caching -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
1.2 添加配置文件 ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<cache name="depts"
eternal="false"
maxEntriesLocalHeap="200"
timeToLiveSeconds="3600">
</cache>
</ehcache>
1.3 在 springboot 的核心配置文件 application.properties 文件里添加 ehcache 配置信息
spring.cache.ehcache.config=classpath:ehcache.xml
1.4 开启缓存
在启动类上加 @EnableCaching 注解启动缓存,也可以加在 缓存配置类上
package com.ahav;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@MapperScan("com.ahav.dao")//扫描 mybatis 包
@EnableCaching
public class ReserveApplication {
private static final Logger logger = LoggerFactory.getLogger(ReserveApplication.class);
public static void main(String[] args) {
SpringApplication.run(ReserveApplication.class, args);
logger.info("======================启动完成=====================");
}
@Autowired
private RestTemplateBuilder builder;
// 使用
// RestTemplateBuilder来实例化RestTemplate对象,spring默认已经注入了RestTemplateBuilder实例
@Bean
public RestTemplate restTemplate() {
return builder.build();
}
}
1.5 在需要缓存的方法上加注释即可使用缓存
@Override
@Cacheable(value = "depts")
public SystemResult viewDeptsAndUsers() {
List<DeptStructure> deptStructure = new ArrayList<>();
// 查询父级部门,即parentId为null的部门
deptDao.selectParentDepts().forEach(parent -> deptStructure.add(new DeptStructure(parent)));
deptStructure.forEach(ds -> packagingDepts(ds));
return new SystemResult(HttpStatus.OK.value(), "组织架构查看", deptStructure);
}