In order to improve the operation efficiency of the system, the cache mechanism is introduced to reduce database access and disk IO. The following describes the Ehcache and Springboot integration configuration
Preface Introduction
EhCache is a pure Java in-process caching framework, which is fast and capable, and is the default Cacheprovider in Hibernate.
Ehcache provides a variety of cache policies, mainly divided into memory and disk level two, so there is no need to worry about capacity issues.
Spring-boot is a fast integration framework designed to simplify the initial construction and development of new spring applications. The framework uses a specific approach to configuration, which eliminates the need for developers to define boilerplate configurations.
Since Spring-boot does not require any boilerplate configuration files, it can be slightly different when Spring-boot integrates some other frameworks.
1.spring-boot is a framework for the jar package managed by MAVEN, and the integration Ehcache requires the following dependencies
<dependency> <groupId>org.springframework</groupId> <artifactId> Spring-context-support</artifactid></dependency><dependency> <groupId> Net.sf.ehcache</groupid>
2. Using Ehcache, we need a ehcache.xml to define some of the cache's properties.
<?xml version="1.0"encoding="UTF-8"?><ehcache> <!--Specify a file directory, and when Ehcache writes the data to the hard disk, the data is written to the file directory--<diskstore path="Java.io.tmpdir"/> <!--Set the default data expiration policy for the cache--<Defaultcache maxelementsinmemory="10000"Eternal="false"Overflowtodisk="true"Timetoidleseconds="Ten"Timetoliveseconds=" -"diskpersistent="false"Diskexpirythreadintervalseconds=" -"/> <cache name="cachetest"maxelementsinmemory=" +"Eternal="false"Overflowtodisk="true"Timetoidleseconds="Ten"Timetoliveseconds=" -"/></ehcache>
Key parameter Description
(1). Diskstore: For the cache path, Ehcache is divided into memory and disk level two, this property defines the cache location of the disk. The parameters are explained as follows:
user.home– User Home Directory
user.dir– User's current working directory
java.io.tmpdir– Default Temporary file path
(2). Defaultcache: The default cache policy, which is used when Ehcache cannot find a defined cache. You can define only one.
(3). Cache: Custom cache policy for a custom cache policy. The parameters are explained as follows:
Properties of the cache element:
Name: Cache names
Maxelementsinmemory: Maximum number of cached objects in memory
Maxelementsondisk: The maximum number of cache objects on the hard disk, if 0 means infinity
Eternal:true indicates that the object never expires, the Timetoidleseconds and Timetoliveseconds properties are ignored, and the default is False
Overflowtodisk:true indicates that when the number of objects in the memory cache reaches the maxelementsinmemory limit, the overflow object is written to the hard disk cache. Note: If the cached object is to be written to the hard disk, the object must implement the Serializable interface.
DISKSPOOLBUFFERSIZEMB: Disk buffer size, default is 30MB. Each cache should have its own cache.
Diskpersistent: Whether to cache virtual machine Restart period data
Diskexpirythreadintervalseconds: Disk failed thread run time interval, default is 120 seconds
Timetoidleseconds: Sets the maximum time, in seconds, that an object is allowed to be idle. When an object has been idle for longer than the Timetoidleseconds property value since the last time it was accessed, the object expires and Ehcache will empty it from the cache. This property is valid only if the Eternal property is false. If the property value is 0, the object can be idle indefinitely
Timetoliveseconds: The maximum amount of time, in seconds, that a set object is allowed to exist in the cache. When an object has been stored in the cache for more than the Timetoliveseconds property value, the object expires and Ehcache clears it from the cache. This property is valid only if the Eternal property is false. If the property value is 0, the object can exist indefinitely in the cache. Timetoliveseconds must be greater than timetoidleseconds attribute to make sense
Memorystoreevictionpolicy: When the maxelementsinmemory limit is reached, Ehcache will clean up the memory according to the specified policy. The optional policies are LRU (least recently used, default policy), FIFO (first in, out), LFU (minimum number of accesses).
3. Exposing the Ehcache Manager to the spring context container
Package Com.ww.ehcache;import Org.springframework.cache.ehcache.ehcachecachemanager;import Org.springframework.cache.ehcache.ehcachemanagerfactorybean;import Org.springframework.context.annotation.Bean; Import Org.springframework.core.io.ClassPathResource; Public classcacheconf {/** Ehcache main manager*/@Bean (Name="Appehcachecachemanager") Publicehcachecachemanager Ehcachecachemanager (Ehcachemanagerfactorybean Bean) {return NewEhcachecachemanager (Bean.getobject ()); } /** According to the settings of shared or not, Spring creates a ehcache base by Cachemanager.create () or new CacheManager () respectively. */@Bean PublicEhcachemanagerfactorybean Ehcachemanagerfactorybean () {Ehcachemanagerfactorybean CacheManagerFactoryBean=NewEhcachemanagerfactorybean (); Cachemanagerfactorybean.setconfiglocation (NewClasspathresource ("Ehcache-setting.xml")); Cachemanagerfactorybean.setshared (true); returnCachemanagerfactorybean; } }
Explain the annotations.
@Configuration: For spring-boot annotations, this is the configuration class, priority scan.
@Bean: Add beans to the spring container.
Now that all the configurations are done, the integration framework through Spring-boot is as simple as that.
4. Using Ehcache
Using Ehcache primarily through spring's caching mechanism, we implemented the spring caching mechanism using the Ehcache, so the use of aspects of the spring cache mechanism is fully used.
A few notes are involved:
@Cacheable: Responsible for adding the return value of the method to the cache, parameter 3
@CacheEvict: Responsible for clearing the cache, parameter 4
Parameter explanation:
Value: The cache location name, cannot be empty, if using Ehcache, is the name of the cache declared in Ehcache.xml
Key: The cached key, which is empty by default, represents both the parameter type and the parameter value of the method used as key, which supports Spel
Condition: Trigger condition, only when the condition is satisfied, the cache is added, the default is empty, both means that all are added to the cache, support Spel
Allentries:cacheevict parameter, true to clear all caches in value, default to False
Interface class
Package Com.ww.service; Public Interface Cache { public string gettimestamp (string param);}
Implementation class
Package Com.ww.service;import Org.springframework.cache.annotation.cacheevict;import Org.springframework.cache.annotation.cacheable;import Org.springframework.stereotype.Service;
Remember to add annotations @service Public classWehcache implements cache{@Cacheable (value="cachetest", key="#param") @Override Publicstring Gettimestamp (string param) {Long timestamp=System.currenttimemillis (); returntimestamp.tostring (); } @CacheEvict (Value="cachetest") Publicboolean deluserrole (String param) {//clean up cache operations return false; } }
Controller Layer Invocation
Package Com.ww.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.requestmapping;import Com.ww.service.Cache; @Controller Public classWebcontroller {@AutowiredPrivateCache Wehcache; @RequestMapping ("/index") PublicString Index (Modelmap map) throws interruptedexception{System. out. println ("First Call:"+ Wehcache.gettimestamp ("param")); Thread.Sleep ( -); System. out. println ("called after 2 seconds:"+ Wehcache.gettimestamp ("param")); Thread.Sleep ( the); System. out. println ("call after 5 seconds:"+ Wehcache.gettimestamp ("param")); return "Index"; } }
Springboot Integrated Ehcache Learning Notes