SpringBoot realizes caching function through @Cacheable annotation | Spring Boot 36

1. Spring supports Cache from 3.1

Spring has introduced support for Cache since 3.1. The org.springframework.cache.Cacheand org.springframework.cache.CacheManagerto unify the different caching techniques. And supports the use of JCache(JSR-107)annotations simplify our development.

Its usage method and principle are similar to Spring's support for transaction management. Spring Cache acts on methods. Its core idea is that when we call a cache method, we will use the method parameters and return results as a key-value pair exists in the cache.
The cache annotation @Cacheable provided in SpringBoot, @Cacheable will use the return value of the method as the value of the cache, and the parameter value of the method as the key of the cache by default. @Cacheable can be marked on a specific method, or it can be marked on a class, indicating that all methods of this class support caching.

Every time a method that requires caching is called, Spring will check whether the specified target method of the specified parameter has been called, and if so, directly obtain the result of the method call from the cache, if not, call the method and cache the result and return it to user, the next call will be obtained directly from the cache.

Two, @Cacheable common attributes

  1. @Cacheable adds cache, queries with the same conditions no longer query the database, but query from the cache;
  2. @CachePut will access the database every time and update the cache;
  3. @CacheEvict clears the cache;
    insert image description here

1、value/cacheNames

As shown in the figure above, these two attributes represent the same meaning. These two attributes are used to specify the name of the cache component, that is, which cache to put the return result of the method in. The attribute is defined as an array, and multiple caches can be specified;

2、key

The key used for caching data can be specified through the key attribute, and the parameter passed by the method call is used as the key by default. The content format stored in the final cache is in the form of Entry<key,value>.

3、condition

Triggering conditions. This parameter specifies the conditional splicing triggered by the cache. For example condition="#area.id != 1", the cache is triggered when the id is not 1.

4、unless

exclusions. This parameter specifies when the cache will not be triggered, for example unless="#result == null", do not cache the result of the query result being NULL.

5、keyGenerator

Custom Key strategy, such as the cached Key value is the method name.

@Configuration
public class CacheConfig{
    
    
	@Bean
	public KeyGenerator myKeyGenerator(){
    
    
		return (target,method,params)->method.getName();
	} 
}

KeyGenerator is a functional interface provided by Spring.

package org.springframework.cache.interceptor;

import java.lang.reflect.Method;

/**
 * Cache key generator. Used for creating a key based on the given method
 * (used as context) and its parameters.
 *
 * @author Costin Leau
 * @author Chris Beams
 * @author Phillip Webb
 * @since 3.1
 */
@FunctionalInterface
public interface KeyGenerator {
    
    

	/**
	 * Generate a key for the given method and its parameters.
	 * @param target the target instance
	 * @param method the method being called
	 * @param params the method parameters (with any var-args expanded)
	 * @return a generated key
	 */
	Object generate(Object target, Method method, Object... params);

}

Specify the Key custom generation strategy through @Cacheable(keyGenerator="myKeyGenerator").

6、sync

Whether to use asynchronous mode, the default is that the method is executed, and the result returned by the method is stored in the cache in a synchronous manner.

7、cacheManager

It can be used to specify the cache manager, from which cache manager to get the cache.

3. Integration steps

1. Join pom

<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2. Add @EnableCaching annotation to the startup class

3. Controller or service can be annotated with @Cacheable

4. Code example

package com.nezha.controller;

import com.nezha.entity.Area;
import com.nezha.service.area.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/area")
public class AreaController {
    
    

    @Autowired
    private AreaService areaService;

	// @Cacheable添加缓存,相同条件的查询不再查询数据库,而是从缓存中查询
    @Cacheable(cacheNames="area",key = "#id")
    @GetMapping("getAreaById")
    public Area getAreaById(Integer id) {
    
    
        return areaService.getAreaById(id);
    }

	// @CachePut每次都会访问数据库,并更新缓存
    @CachePut(cacheNames="area",key = "#id")
    @PostMapping("updateAreaById")
    public void updateAreaById(Integer id) {
    
    
        areaService.updateAreaById(id);
    }

	// @CacheEvict清除缓存
    @CacheEvict(cacheNames="area",key = "#id")
    @PostMapping("deleteAreaById")
    public void deleteAreaById(Integer id) {
    
    
        areaService.deleteAreaById(id);
    }
}

Through postman access 127.0.0.1:8080/NettyProject/area/getAreaById?id=1, the console outputs sql logs for the first time, and the console does not output logs for the second request, which proves that no sql query is performed, and the query is the @Cacheable(cacheNames="area",key = "#id")cached data.



Nezha Boutique Series Articles

Summary of Java learning route, brick movers attack Java architects

Summary of 100,000 words and 208 Java classic interview questions (with answers)

Java Basic Tutorial Series

Java High Concurrency Programming Series

Database Advanced Combat Series

Spring security principles and mechanisms | Spring Boot 35

ShardingSphere sub-database sub-table tutorial | Spring Boot 34
insert image description here

Guess you like

Origin blog.csdn.net/guorui_java/article/details/127163597