Detailed explanation of springboot ehcache configuration usage code

  • 2021-10-11 18:43:09
  • OfStack

EhCache is a mature Java cache framework, which was first developed from hibernate. It is an in-process cache system. It provides a variety of flexible cache management schemes such as memory, disk file storage and distributed storage, which are fast and simple.

Springboot is very supportive of ehcache, so it can be used only by making some configuration in Springboot, and it is easy to use.

The following is an introduction to the use of springboot ehcache configuration through this article. The specific contents are as follows:

1. pom introduces dependencies


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

2. Put a file ehcache. xml directly under the resources directory


<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 Default cache policy for   -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
        
    <!--  Menu caching strategy  -->
    <cache name="menucache"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
    
</ehcache>

3. Annotate the Service layer method

@ CacheEvict (value= "menucache", allEntries=true), update cache

@ Cacheable (key= "'menu-' + # parentId", value= "menucache") reads the cache, "'menu-' + # parentId" wildcard characters, or directly writes dead strings

menucache corresponds to xmlname= "menucache" above


/** Delete menu 
	 * @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);
	}

	/**
	 *  Pass ID Get its children 1 Level menu 
	 * @param parentId
	 * @return
	 * @www.fhadmin.org
	 */
	@Cacheable(key="'menu-'+#parentId",value="menucache")
	public List<Menu> listSubMenuByParentId(String parentId) throws Exception {
		return menuMapper.listSubMenuByParentId(parentId);
	}

Related articles: