程序员社区

soringboot ehcache 配置和用法

1.pom

		<!-- Ehcache -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>

2. application.properties

#缓存配置文件位置
spring.cache.ehcache.cofnig=ehcache.xml

3. 在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>

4.读取缓存 在 serviceImpl 层,例:MenuServiceImpl

    /**java项目 www.fhadmin.org
	 * 通过ID获取其子一级菜单
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	@Cacheable(key="'menu-'+#parentId",value="menucache")
	public List<Menu> listSubMenuByParentId(String parentId) throws Exception {
		return menuMapper.listSubMenuByParentId(parentId);
	}

加入的注解 @Cacheable(key="'menu-'+#parentId",value="menucache") ,其中 key="'menu-'+#parentId" 是指相应的键,#parentId 是通配符,和参数名对应,key 也可以是固定的字符, value="menucache" 中的  menucache 是 ehcache.xml中缓存策略中的name

5.清除缓存,也在在 serviceImpl 层,例:MenuServiceImpl   加入注解 @CacheEvict(value="menucache", allEntries=true)

/**保存修改菜单 java项目 www.fhadmin.org
	 * @param menu
	 * @throws Exception
	 */
	@CacheEvict(value="menucache", allEntries=true)
	public void edit(Menu menu) throws Exception{
		menuMapper.edit(menu);
	}

赞(0) 打赏
未经允许不得转载:IDEA激活码 » soringboot ehcache 配置和用法

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区