1.pom.xml中添加依賴。spring-boot-starer-cache中已經有了ehcache和cache-api,可以不用再添加。
<!-- 本機快取依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><!-- <dependency><groupId>org.ehcache</groupId><artifactId>ehcache</artifactId></dependency><dependency><groupId>javax.cache</groupId><artifactId>cache-api</artifactId></dependency> -->
2. application.properties檔案中添加配置位置。指定使用的cacheManger是jcache。
#-------------------ehcache----------------------spring.cache.jcache.config=classpath:/config/ehcache.xml
3. 在配置的目錄中建立添加ecache.xml檔案。更詳細的可以參照官方文檔
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xmlns:jsr107="http://www.ehcache.org/v3/jsr107" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.2.xsd http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.2.xsd"><persistence directory="java.io.tmpdir"/><cache-template name="default"> <resources> <heap unit="entries">2000</heap> <offheap unit="MB">100</offheap> </resources> </cache-template> <cache alias="SSAccountInfo" uses-template="default"> <expiry> <ttl unit="seconds">600</ttl> </expiry> </cache> </config>
3.在配置類或者啟動類上面,添加啟用緩衝的註解
@EnableCaching
4 . 在需要緩衝的資料方法上面打上緩衝註解。幾個常用的緩衝註解可參照官網。
package com.caiwufei.module.cfsss.dao;import org.springframework.cache.annotation.Cacheable;import com.caiwufei.entity.base.BaseMapper;import com.caiwufei.entity.cfsss.SSAccountInfo;public interface SSAccountInfoDao extends BaseMapper<SSAccountInfo>{@Cacheable(cacheNames="SSAccountInfo", unless="#result==null")public SSAccountInfo queryAccountInfoById(SSAccountInfo a);}