Spring Boot Learning (13) Springboot cache (EhCache 2.x)

Source: Internet
Author: User
Tags current time time interval uuid
springboot Cache (EhCache 2.x) Springboot Cache


In spring boot, the appropriate cache manager (CacheManager) is configured with @enablecaching 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:
The cache abstraction does not provide actual storage and relies on abstractions implemented by the Org.springframework.cache.Cache and Org.springframework.cache.CacheManager interfaces. Spring boot automatically configures the appropriate CacheManager based on the implementation, as long as the cache support is enabled via the @enablecaching annotation. 

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 following dependencies are introduced in the Pom.xml 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


Create the file Ehcache.xml under the Resource folder 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


Some of the data is from the network Diskstore: for the cache path, Ehcache is divided into memory and disk level two, this property defines the cache location of the disk. 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 is timetoidleseconds: sets the allowable idle time (in seconds) before the object 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 plus the annotation @enablecaching that opens the cache. 

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



@Mapper public
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: To provide SQL statements for Dao interface methods->

     <!-Map entity object->
     <resultMap id = "UserResultMap" type = "qg.fangrui.boot.model.User">
         <id property = "id" column = "id" />
         <result property = "uuid" column = "uuid" />
         <result property = "name" column = "name" />
         <result property = "age" column = "age" />
     </ resultMap>


     <insert id = "save">
         INSERT INTO users (name, age, uuid)
         VALUES (# {user.name}, # {user.age}, # {user.uuid})
     </ insert>

     <select id = "findByUuid" resultType = "User">
         SELECT * FROM users WHERE uuid = # {uuid}
     </ select>

     <delete id = "delete">
         DELETE FROM users WHERE uuid = # {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 can also declare a method to support the caching feature. The method that uses the @cacheput annotation does not check the cache for previous results before execution, 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


@Service
public class UserService {

    // The single quotes here must not be less, otherwise it will report an error and be identified 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")
    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) throws 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) {
        // If the cache cannot be found, a prompt statement will be printed
        System.err.println ("No cache taken." + 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


@RestController
public class EhcacheController {

    private static final Logger logger = LoggerFactory.getLogger (EhcacheController.class);

    @Autowired
    private UserService userService;

    @RequestMapping ("/ encache")
    public String EhcacheTest () {
        logger.debug ("Perform the Encache cache test");
        System.out.println ("==== Generate the first user ====");
        User user1 = new User ();
        // Generate the unique identifier UUID of the first user
        String u1_uuid = UUID.randomUUID (). ToString ();
        // Remove the UUID-symbol
        String uuid1 = u1_uuid.substring (0,8) + u1_uuid.substring (9,13) + u1_uuid.substring (14,18) + u1_uuid.substring (19,23) + u1_uuid.substring (24);
        user1.setName ("Zhang San");
        user1.setAge (18);
        user1.setUuid (uuid1);
        if (userService.save (user1) == 0) {
            throw new JdbcException ("The user object failed to insert into the database");
        }

        // First query
        System.out.println (userService.findByUuid (user1.getUuid ()));
        // Query through cache
        System.out.println (userService.findByUuid (user1.getUuid ()));

        System.out.println ("==== Modify data ====");
        User user2 = new User ();
        user2.setName ("李四 -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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.