springboot 加快取
阿新 • • 發佈:2018-11-06
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);
}