Using Caching in Springboot

Source: Internet
Author: User

In the development, if the same query criteria to frequently query the database, will it bring great pressure on the database?
therefore, we need to cache the queried data so that the client only needs to query the data once from the database and then put it in the cache, which can be read from the cache later when it is queried again.
Spring3 began to provide powerful annotation-based caching support, which can increase the caching capability of the original spring application by using the annotation configuration method, and improve the data access Performance.

The following cache is used specifically in springboot:

1. In pom.xml, introduce cache dependency and add the Following:

< Dependency >    < groupId >org.springframework.boot</groupId>    <  Artifactid>spring-boot-starter-cache</artifactid> </ Dependency >

2. Add @enablecaching annotations on the spring boot main class to turn on the cache function as Follows:

@SpringBootApplication @enablecaching  public class application {    publicstaticvoid  main (string[] Args) {        Springapplication.run (application. class , args);}    }

3. In the data access interface, add the cache configuration annotations, such as:

@CacheConfig (cachenames = "users")publicinterfaceextends jparepository<user, long> {    @Cacheable    User findbyname (String name);}

Springboot supports a variety of caching methods: redis, guava, ehcahe, jcache, and More.

description of the difference between Redis and ehcache:

Redis: a standalone running program that needs to be installed separately and manipulated using Jedis in Java. Because it is independent, so if you write a unit test program, put some data in redis, and then write a program to get the data, then you can get this Data. ,
Ehcache: Unlike redis, which is tied to Java programs, the Java program is alive and Alive. For example, write a separate program to put the data, and then write a separate program to get the data, then you can not get the Data. Data can only be obtained in a standalone Program.

If you use ehcache, simply add the Ehcache.xml profile to your project and add Ehcache dependencies to the pom.xml, and the framework will create a Ehcache cache manager whenever it discovers the File.

1. Create in Src/main/resources directory: ehcache.xml

<EhcacheXmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"xsi:nonamespaceschemalocation= "ehcache.xsd">    <Cachename= "users"Maxentrieslocalheap= "$"Timetoliveseconds= "all">    </Cache></Ehcache>

Configuration files for Ehcache can also be specified by using the Spring.cache.ehcache.config attribute in the application.properties file, such as:

Spring.cache.ehcache.config=classpath:config/another-config.xml

2, Add in the Pom.xml

< Dependency >    < groupId >net.sf.ehcache</groupId>    <Artifactid  >ehcache</artifactid></  Dependency>



Cache Annotations
  • @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 the name of the cache set that we configure without using that annotation @Cacheable .

  • @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 added for spring 4, as value aliases) for specifying the collection name of the cache Store. Since spring 4 is new @CacheConfig , the attributes that are required in Spring 3 are value also non-essential.
    • key: The cache object is stored in the map collection of the key value, not required, by default according to all parameters of the function as the key value, if you configure the use of Spel expression, such as: @Cacheable(key = "#p0") : using the first parameter of the function 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 need to use the Spel expression, only content that satisfies the expression condition will be cached, for Example: @Cacheable(key = "#p0", condition = "#p0.length() < 3") , indicates that only when the length of the first parameter is less than 3 is cached, if the AAA user above this configuration will not be cached, the reader can experiment with their own.
    • unless: Another cache condition parameter, not required, requires the use of a spel Expression. It differs from the argument in that it is judged by condition its timing, which is judged only after the function has been 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 that parameter to Specify. It is important to note that this parameter key is mutually exclusive
    • 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. org.springframework.cache.interceptor.CacheResolveran 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 a function, can be cached according to the parameters of the definition, it @Cacheable is different, it is really called function every time, so it is mainly used for data addition and modification Operations. Its parameters and @Cacheable similar, The specific function can refer to @Cacheable the analysis of the parameters on the face
    • @CacheEvict: Configured on a function, typically used on a delete method, to remove the data from the Cache. In addition @Cacheable to the same parameters, it has the following two parameters:
      • allEntries: Not required, default is False. When true, all data is removed
      • beforeInvocation: Not required, The default is false, which removes the data after the method is Called. When true, data is removed before the method is Called.

Using Caching in Springboot

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.