1. pom 引入依賴
<!-- Ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

2.resources 目錄下直接放個檔案 ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<!--defaultCache:echcache的默認快取策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- 選單快取策略 -->
<cache name="menucache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>

3.在Service層 方法上加上注解
@CacheEvict(value="https://www.cnblogs.com/teacher11/p/menucache", allEntries=true) ,更新快取
@Cacheable(key="'menu-'+#parentId",value="https://www.cnblogs.com/teacher11/p/menucache") 讀取快取, "'menu-'+#parentId" 通配符,也可以直接寫死字串
menucache 對應 上面 xml name="menucache"
/**洗掉選單
* @param MENU_ID
* @www.fhadmin.org
*/
@CacheEvict(value="https://www.cnblogs.com/teacher11/p/menucache", allEntries=true)
public void deleteMenuById(String MENU_ID) throws Exception{
this.cleanRedis();
menuMapper.deleteMenuById(MENU_ID);
}
/**
* 通過ID獲取其子一級選單
* @param parentId
* @return
* @www.fhadmin.org
*/
@Cacheable(key="'menu-'+#parentId",value="https://www.cnblogs.com/teacher11/p/menucache")
public List<Menu> listSubMenuByParentId(String parentId) throws Exception {
return menuMapper.listSubMenuByParentId(parentId);
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/288422.html
標籤:Java
