springboot ehcache 配置使用方法

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="menucache", allEntries=true) ,更新緩存

@Cacheable(key="'menu-'+#parentId",value="menucache")  讀取緩存, "'menu-'+#parentId" 通配符,也可以直接寫死字符串

menucache 對應 上面 xml name="menucache" 

	/**刪除菜單
	 * @param MENU_ID
	 * @www.fhadmin.org
	 */
	@CacheEvict(value="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="menucache")
	public List<Menu> listSubMenuByParentId(String parentId) throws Exception {
		return menuMapper.listSubMenuByParentId(parentId);
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章