soringboot ehcache 配置和用法

1220阅读 0评论2021-04-25 fhadmin
分类:Java


1.pom

点击(此处)折叠或打开


  1.         <dependency>
  2.             <groupId>net.sf.ehcache</groupId>
  3.             <artifactId>ehcache</artifactId>
  4.         </dependency>

2. application.properties

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

3. 在resources目录下放一个文件 ehcache.xml

点击(此处)折叠或打开

  1. <ehcache xmlns:xsi="
  2.          xsi:noNamespaceSchemaLocation="
  3.          updateCheck="false">
  4.     <diskStore path="java.io.tmpdir"/>
  5.   <!--defaultCache:echcache的默认缓存策略 -->
  6.     <defaultCache
  7.             maxElementsInMemory="10000"
  8.             eternal="false"
  9.             timeToIdleSeconds="120"
  10.             timeToLiveSeconds="120"
  11.             maxElementsOnDisk="10000000"
  12.             diskExpiryThreadIntervalSeconds="120"
  13.             memoryStoreEvictionPolicy="LRU">
  14.         <persistence strategy="localTempSwap"/>
  15.     </defaultCache>
  16.     
  17.     
  18.     <!-- 菜单缓存策略 -->
  19.     <cache name="menucache"
  20.             maxElementsInMemory="10000"
  21.             eternal="false"
  22.             timeToIdleSeconds="120"
  23.             timeToLiveSeconds="120"
  24.             maxElementsOnDisk="10000000"
  25.             diskExpiryThreadIntervalSeconds="120"
  26.             memoryStoreEvictionPolicy="LRU">
  27.         <persistence strategy="localTempSwap"/>
  28.     </cache>
  29.     
  30. </ehcache>


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

    /**java项目 www fhadmin org
	 * 通过ID获取其子一级菜单
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	@Cacheable(key="'menu-'+#parentId",value="menucache")
	public List
	
		 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)







上一篇:Java 读取 Word文本、段落格式属性
下一篇:Java 读取 Word 文本中的标题