ITPub博客

首页 > 应用开发 > Java > soringboot ehcache 配置和用法

soringboot ehcache 配置和用法

原创 Java 作者:fhadmin 时间:2021-04-25 13:14:15 0 删除 编辑

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="
         xsi:noNamespaceSchemaLocation="
         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

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

加入注解 @CacheEvict(value="menucache", allEntries=true)


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31558068/viewspace-2769714/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-10-12

  • 博文量
    310
  • 访问量
    166455