Springboot Cache (EhCache 2.x) Springboot cache
In spring boot, the @EnableCaching
appropriate cache manager (CacheManager) is configured with annotation automation, and Spring boot detects the cache provider according to the following sequence:
* Generic
* Jcache (JSR-107)
* EhCache 2.x
* Hazelcast
* Infinispan
* Redis
* Guava
* Simple
About the cache mechanism for Spring Boot:
Cache abstraction does not provide actual storage, and relies on org.springframework.cache.Cache
org.springframework.cache.CacheManager
abstractions implemented by and interfaces. Spring boot automatically configures the appropriate CacheManager based on the implementation, as long as the cache support is @EnableCaching
enabled via annotations.
Spring Boot Configuration EhCache 2.x
There is very little information on the annotations cache in the official documentation, which often requires us to understand the corresponding cache provider. What I'm mainly introducing here is the EhCache.
Introducing Dependencies
The pom.xml
following dependencies are introduced in the file
<!--open Cache Cache-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!--ehcache Cache-- > <dependency> <groupId>net.sf.ehcache</groupId> <artifactid>ehcache </artifactId> </dependency>
Introducing the configuration file Ehcache.xml
resource
create a file under a folder ehcache.xml
and configure it:
<?xml version= "1.0" encoding= "UTF-8"? ><ehcache xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation= "http://ehcache.org/ehcache.xsd" updatecheck= "false" > < Defaultcache eternal= "false" maxelementsinmemory= "" " overflowtodisk=" false " diskpersistent= "False" timetoidleseconds= "0" timetoliveseconds= "memorystoreevictionpolicy=" "LRU"/> <!--Here the users cache space is ready for the demo below- <cache name= "users" eternal= "false" maxelementsinmemory= "overflowtodisk=" false " diskpersistent=" false " timetoidleseconds=" 0 " " timetoliveseconds=" memorystoreevictionpolicy= "LRU"/></ehcache>
Ehcache.xml File Configuration Detailed:
- Diskstore: For the cache path, Ehcache is divided into memory and disk level two, which defines the disk's cache location.
- Defaultcache: The default cache policy, which is used when Ehcache cannot find a defined cache. You can define only one.
- Name: Cache names.
- Maxelementsinmemory: Maximum number of caches
- Maxelementsondisk: Maximum number of hard disk caches.
- Eternal: The object is permanently valid, but if set, timeout will not work.
- Overflowtodisk: Whether to save to disk, when the system when the machine
- Timetoidleseconds: Sets the allowable idle time (in seconds) for an object before it expires. An optional property is used only if the Eternal=false object is not permanently valid, and the default value is 0, which means that the idle time is infinite.
- Timetoliveseconds: Sets the time (in seconds) that an object is allowed to survive before it expires. The maximum time is between the creation time and the expiration time. Used only when the Eternal=false object is not permanently valid, the default is 0, which means that the object survives indefinitely.
- Diskpersistent: Whether to cache VM Restart period data Whether The disk store persists between restarts of the virtual machine. The default value is FALSE.DISKSPOOLBUFFERSIZEMB: This parameter sets the buffer size of the Diskstore (disk cache). The default is 30MB. Each cache should have its own buffer.
- Diskexpirythreadintervalseconds: Disk failed thread run time interval, default is 120 seconds.
- Memorystoreevictionpolicy: When the maxelementsinmemory limit is reached, Ehcache will clean up the memory according to the specified policy. The default policy is LRU (least recently used). You can set it to FIFO (first in, out) or LFU (less used).
- Clearonflush: If the maximum amount of memory is cleared.
- Memorystoreevictionpolicy: The optional policies are: LRU (least recently used, default policy), FIFO (first in, out), LFU (minimum number of accesses).
Fifo,first in First out, FIFO.
LFU, less frequently used, has been used at least for a long time. As mentioned above, the cached element has a hit attribute, and the least hits value will be cleared out of the cache.
Lru,least recently used, the least recently used, the cached element has a timestamp, and when the cache is full, and you need to make room to cache the new element, the elements in the existing cache element with the longest timestamp from the current time are cleared out of the cache.
Add a start note to the main class
In the Spring Boot main class, add the annotations that open the cache @EnableCaching
.
Demo:springboot + ehcache build Spring Boot Project
I set up an ordinary Springboot project and configured the Druid+mysql.
The users table is created in the database and the fields are as follows:
Field name |
Properties |
Id |
bigint |
Uuid |
varchar |
Name |
varchar |
Age |
Int |
User entity class
User.java
public class User { private long ID; Private String uuid; private String name; Private Integer age; Omit get, set, and ToString methods}
User Database Operation interface
Userdao.java
@Mapperpublic interface userdao{ void Delete (String uuid); User update (user user); User Findbyuuid (String uuid); int Save (@Param ("user") user user);
User Action Mapper File
Usermapper.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace= "Qg.fangrui.boot.dao.UserDao" > <!--Purpose: Provide SQL statements to the DAO interface method--<!--Map entity objects--and <re Sultmap id= "Userresultmap" type= "Qg.fangrui.boot.model.User" > <id property= "id" column= "id"/> < Result property= "uuid" column= "uuid"/> <result property= "name" column= "name"/> <result propert Y= "Age" column= "age"/> </resultMap> <insert id= "Save" > Insert to Users (name, age, UUID) VALUES (#{user.name}, #{user.age}, #{user.uuid}) </insert> <select id= "Findbyuuid" resulttype= "user" ; SELECT * from the users where uuid = #{uuid} </select> <delete id= "Delete" > Delete from Users where u UID = #{uuid} </delete></mapper>
User Operation Service Layer
In general, we perform a cache operation on the sercive layer. Let's first introduce Ehcache's annotations in spring: In the context of supporting spring Cache,
* @Cacheable
: Spring checks to see if there is a cache element of the same key in the cache before each execution, and if it does not execute the method, it returns the result directly from the cache, otherwise it is executed and the returned result is stored in the specified cache.
* @CacheEvict
: Clears the cache.
* @CachePut
: @CachePut
You can also declare a method to support cache functionality. The @CachePut
method used for labeling does not check for the existence of previously executed results in the cache until it executes, but executes the method every time and stores the execution result as a key-value pair in the specified cache.
* There are two main attributes in all three methods: value refers to the cache policy space in Ehcache.xml, key refers to the cached identity and can be referenced by #.
Userservice.java
@Servicepublic class UserService {//Here the single quotation mark can not be less, otherwise will error, is recognized as an object private static final String Cache_key = "' User '"; private static final String Demo_cache_name = "users"; @Autowired private Userdao Userdao; Delete user Data @CacheEvict (value = Demo_cache_name,key = "' user_ ' + #uuid")//This is clear cache public void Delete (String uuid) { Userdao.delete (UUID); }//Update user data @CachePut (value = Demo_cache_name,key = "' user_ ' + #user. Getuuid ()") Public user update (user user) throw s cacheexception{User user1 = Userdao.findbyuuid (User.getuuid ()); if (null = = User1) {throw new Cacheexception ("Not Find"); } user1.setage (User.getage ()); User1.setname (User.getname ()); return user1; }//Find user Data @Cacheable (value=demo_cache_name,key= "' user_ ' + #uuid") Public user Findbyuuid (String uuid) {//Search for Not to cache will print out prompt statement System.err.println ("No walk cache!") "+uuid); return Userdao.findbyuuid (UUID); }//Save user Data @CacheEvict (valUe=demo_cache_name,key=cache_key) public int Save (user user) {return userdao.save (user); }}
Controller class
Finally, we create a Controller to access our cache. Because my springboot is in Debug mode, all the database operations will be printed out, this way the cache function can be at a glance.
Ehcachecontroller.java
@RestControllerpublic class Ehcachecontroller {private static final Logger Logger = Loggerfactory.getlogger (Ehcachecon Troller.class); @Autowired private UserService UserService; @RequestMapping ("/encache") public String ehcachetest () {logger.debug ("Encache cache Test"); System.out.println ("= = = The first user = = = ="); User User1 = new user (); Generates a unique identifier for the first user UUID String u1_uuid = Uuid.randomuuid (). toString (); Remove UUID-Symbol String UUID1 = u1_uuid.substring (0,8) +u1_uuid.substring (9,13) +u1_uuid.substring (14,18) +u1_uuid.sub String (19,23) +u1_uuid.substring (24); User1.setname ("Zhang San"); User1.setage (18); User1.setuuid (UUID1); if (Userservice.save (user1) = = 0) {throw new Jdbcexception ("user object inserted into database failed"); }//First query System.out.println (Userservice.findbyuuid (User1.getuuid ())); Query System.out.println by Cache (Userservice.findbyuuid (User1.getuuid ())); System.out.println ("= = modified numberAccording to the = = = "); User User2 = new user (); User2.setname ("John Doe-update"); User2.setage (22); User2.setid (User1.getid ()); User2.setuuid (User1.getuuid ()); try {System.out.println (userservice.update (user2)); } catch (Cacheexception e) {e.printstacktrace (); } System.out.println (Userservice.findbyuuid (User2.getuuid ())); Return "Success"; }}
Test
Start the Springboot project, access the Http://localhost:8080/encache, and view the console printing information:
From the console, we can clearly see that the first time the user information is queried, the project will put the user information into the cache; In the second query, you do not need to access the database to get user information directly from the cache.
Personal reference items:
Personal Reference Project: Https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B9
Spring Boot Learning (13) Springboot cache (EhCache 2.x)