1. Scene Restore
Recently, because the project involves the cache of related data, previously also wrote the Redis cache blog; But the author thinks Ehcache is compared with it, the configuration is simple, also easy to get started, so today introduces how to integrate Ehcache in Springboot Project 2. Implementation plan
① Import Ehcache Dependent
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-cache</artifactid>
<version>1.4.2.RELEASE</version>
</ Dependency>
<!--https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-
<dependency >
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.3</version>
</dependency>
② the Springboot startup class configuration supports cache configuration @enablescheduling
@SpringBootApplication
@MapperScan (basepackages = "Com.cckj.dao", Markerinterface =mapper.class)
@ enablecaching
@EnableScheduling Public
class application extends Springbootservletinitializer {
private static Logger Logger = Loggerfactory.getlogger (application.class);
@Override
protected Springapplicationbuilder Configure (Springapplicationbuilder builder) {
return Builder.sources (Application.class);
}
public static void Main (string[] args) {
springapplication.run (application.class, args);
Logger.info ("My Spring Boot application Started");
}
}
③ Creating a Ehcache.xml file under the Resources directory
<?xml version= "1.0" encoding= "UTF-8"?> <ehcache
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance "xsi:nonamespaceschemalocation=" http://ehcache.org/ehcache.xsd ">
<diskstore path=" java.io.tmpdir/ Ehcache "/>
<!--set the default data expiration policy for the cache--
<defaultcache
maxelementsinmemory="
eternal= " False "
overflowtodisk=" true "
timetoidleseconds=" "timetoliveseconds=" "
diskpersistent=" False "
diskexpirythreadintervalseconds="/>
<cache name= "users"
maxelementsinmemory= " "
eternal=" false "
overflowtodisk=" true "
timetoidleseconds=" 1 "
timetoliveseconds=" 20 "/ >
</ehcache>
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 means 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). ④ Configuration in Application.properities
#ehcache配置
Spring.cache.jcache.config=classpath:ehcache.xml
⑤ Implementing cache annotation Configuration in an implementation class
@Override
@Cacheable (value = "users", key = "#param") public
String gettimestamp (string param) {
Long timestamp = System.currenttimemillis ();
return timestamp.tostring ();
}
The users here are the name of the cache in the front ehcache.xml;
Confirm the expiration time of the cache before testing
<!--set the default data expiration policy for the cache--
<defaultcache
maxelementsinmemory= "$"
eternal= "false"
Overflowtodisk= "true"
timetoidleseconds= "ten"
timetoliveseconds= "
diskpersistent=" false "
diskexpirythreadintervalseconds= "/>
<cache name=" users "
maxelementsinmemory="
Eternal= "false"
overflowtodisk= "true"
timetoidleseconds= "
timetoliveseconds="/>
The cache expiration time for the users is timetoidleseconds to 10s, that is, when more than 10 caches are automatically erased
⑥ Test class:
@Test public
void Test1 () throws interruptedexception {
String first = userservice.gettimestamp ("param");
System.out.println ("First Call:" +first);
Thread.Sleep (the);
String second = userservice.gettimestamp ("param");
System.out.println ("Second call:" +second);
Thread.Sleep (30000);
String third = userservice.gettimestamp ("param");
System.out.println ("Third call:" +third);
}
Effect Diagram:
The first time is the same as the second result, the third time is different from the first two, because the second time is in cache time of 10s, but the third time is not within the cache's cached time, so it is different from the previous two. 3.ehcache Annotation Explanation
@CacheConfig: Used primarily to configure some common cache configurations that are used in this class. Here @cacheconfig (cachenames = "users"): The content returned in this data Access object is configured to be stored in a cache object named users, and we can also define it directly by @cacheable the name of the cache set that you configure by itself, without using the annotation.
@Cacheable: The return value configured with the Findbyname function is added to the cache. At the same time, the query is fetched from the cache, and if it does not exist, then access to the database is initiated. The note has the following main parameters:
Value, Cachenames: two equivalent parameters (Cachenames is new for Spring 4, as an alias for value), specifying the collection name of the cache store. Because of the new @cacheconfig in spring 4, the Value property that was required in Spring 3 is also not required.
Key: The cache object stored in the map collection of the key value, not required, by default all parameters of the function as the key value, if you configure the use of Spel expression, such as: @Cacheable (key = "#p0"): Using the function of the first parameter as the key value of the cache, More details on Spel expressions can be found in the official documentation
Condition: The condition of the cached object, not required, also requires the use of the Spel expression, only content that satisfies the expression condition is cached, such as: @Cacheable (key = "#p0", condition = "#p0. Length () < 3"), Indicates that the first parameter will be cached only if it is less than 3, and if the AAA user above this configuration is not cached, the reader can try it on its own.
Unless: Another cache condition parameter, not required, requires the use of a spel expression. It differs from the condition parameter where it is judged by its timing, which is judged after the function is called, so it can be judged by the result.
Keygenerator: Used to specify the key generator, not required. If you need to specify a custom key generator, we need to implement the Org.springframework.cache.interceptor.KeyGenerator interface and use this parameter to specify. It is important to note that this parameter is mutually exclusive to key
CacheManager: Used to specify which cache manager to use, not required. Only need to use when there are multiple
Cacheresolver: Used to specify that the cache parser is used, not required. The Org.springframework.cache.interceptor.CacheResolver interface is required to implement its own cache parser, which is specified with this parameter.
In addition to the two annotations used here, there are several core annotations:
@CachePut: Configured on the function, can be cached according to the parameters of the definition of the condition, it is different from @cacheable, it is really called function every time, so it is mainly used for data addition and modification operations. Its parameters are similar to @cacheable, the specific function can refer to the analysis of the @cacheable parameters on the face
@CacheEvict: Configured on a function, typically used on a delete method, to remove the data from the cache. In addition to the same parameters as @cacheable, it has the following two parameters: Allentries: Not required, default is False. When True, all data beforeinvocation is removed: Not required, false by default, and data is removed after the method is called. When True, data is removed before the method is called.
Well, today's ehcache to this end, I am Zhang Xing Zhaoyuan, welcome to join the BO Master Technology Exchange Group, Group No.: 313145288