Recommended article reading

Click me to Read SpringBoot and caching ~ concepts, annotations, Redis integration, distributed locking

Click Me to Read SpringBoot Cache how SpringBoot cache works and how @cacheable runs

Click Me to Read SpringBoot

Click me to download

preface


Before trying to write S p r i n g B o o t Advanced article integration of various technologies, has been delayed to write, now to make up for everyone sorry \color{red} before I want to write SpringBoot advanced article integration of various technologies, has been not written, now give everyone to make up the sorry

There are many Redis blogs that SpringBoot integrates, and the general pattern is

  1. The introduction of Pom
  2. Configure Redis
  3. Annotate with @redistemplate annotation

Then redisTemplate. OpsForValue (), redisTemplate opsForList () method to operate

If you are asked to integrate Redis, you will have no problem following these articles. Color {# f6941D} If you want to integrate Redis, follow these articles without any problem. If you are asked to integrate Redis, you will have no problem following these articles. Color {# f6941D} but you will “know how and not know why”, maybe you will integrate, but you do not understand the details of the period, maybe you will integrate, This article focuses on the concept of caching, caching annotations, and integrating Redis. The core of this article is caching annotations, and integrating Redis and serialization mechanism. If you want to learn the RedisTemplate Api, it’s recommended that you bypass it. It’s not about using the Api in detail, it’s more about general knowledge.

Cache concept

As the experience, many people tend to learn more about how to use specific techniques rather than ideas. \color{red} As the experience, many people tend to learn more about how to use specific techniques, but less about ideas. As the experience, many people tend to learn more about how to use specific techniques rather than ideas. To know a word: the theory of flying in the sky, there must be landing products, cache is the idea, redis is its landing products to know a word: the theory of flying in the sky, there must be landing products, cache is the idea, redis is its landing products to know a word: The theory of flying in the sky, there is bound to be landing products, cache is the concept, Redis is its landing products not only this one, a dozen or even dozens of landing products, only by mastering this theory, can we draw conclusions from one point of view, a better understanding of landing products \color{red} landing products not only this one, a dozen or even dozens of products, Only by mastering this theory, can we better understand the landing products, there is not only this one, a dozen or even dozens of landing products, only by mastering this theory, can we better understand the landing products

Java Caching ~ JSR107 specifications

Java Caching defines five core interfaces, namely, CachingProvider, CachingManager, Cache, Entry, and Expiry

  • CachingProvider defines how to create, configure, obtain, manage, and control multiple CacheManager. An application can access multiple CachingProviders at run time.
  • CacheManager defines the creation, configuration, acquisition, management, and control of multiple uniquely named caches. These caches reside in the CacheManager context. A CacheManager is owned by only one CachingProvider
  • A Cache is a map-like data structure that temporarily stores key-indexed values. A Cache is owned by only one CacheManager
  • Entry is a key-value pair stored in the Cache
  • Expiry Every entry stored in the Cache has a defined Expiry date. Once this time is exceeded, the entry is expired

In the state. Once expired, entries are inaccessible, updated, and deleted. The expiration date of a cache can be set using ExpiryPolicy【 Example 】 With concrete examples to understand

Cache annotations

Project preparation

SpringBoot integration mybatis-plus, the process is not demonstrated, directly on the code

@cacheable caches the results of a method based on its request parameters

If you want to use cached annotations, you must EnableCaching and annotate the startup class with @enablecachingCase 1: Repeated query of employee information without caching and repeated query of employee information with caching annotations

@Cacheable(cacheNames = "emp")
	public Employee get(Integer id){
		return employeeMapper.selectById(id);
	}
Copy the code

@cachable annotation attribute explanation

CacheNames/Value: Specifies the name of the cache component. Multiple names are required. For example, the employee cache component and the department cache component can also be specified simultaneously

	@Cacheable(cacheNames = {"emp", "department"})
Copy the code

SPEL: #id, #a0, #p0, #root.argsp[0] SPEL: #id, #p0, #root.argsp[0]

Example 2: If the key is set to 1, the cache is directly queried regardless of the query ID after the first database lookup, indicating that the default key is used

@Cacheable(cacheNames = {"emp", "department"}, key = "1")
@Cacheable(cacheNames = {"emp", "department"}, key = #id)
Copy the code

KeyGenerator: {color{red}} {key {red}} {key {red}} {key {red} {key {red}} KeyGenerator keyGenerator keyGenerator keyGenerator keyGenerator keyGenerator

/ * * *@author xiaozheng
 * @version 1.0
 * @date2020/11/24 15:33 the * /
@Configuration
public class MyCacheConfig {

	@Bean("myKeyGenerator")
	public KeyGenerator keyGenerator(a){
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				return method.getName() + "[" + Arrays.asList(params).toString() + "]"; }}; }}Copy the code

@Cacheable(cacheNames = {"emp", "department"}, keyGenerator = "myKeyGenerator")
	public Employee get(Integer id){
		return employeeMapper.selectById(id);
	}
Copy the code

If the key is a random number, the database will be queried

Condition: the SPEL expression is supported and cached only when this condition is met. Otherwise, the cache is not cached.

@Cacheable(cacheNames = {"emp", "department"}, keyGenerator = "myKeyGenerator", condition = "#id > 1" )
Copy the code

Observations,

Unless: Cache is denied, unless condition is true, cache only if unless condition is false case 5:

// If the query id is greater than 1 and the id is less than 5, the cache will be cached
	@Cacheable(cacheNames = {"emp", "department"}, keyGenerator = "myKeyGenerator", condition = "#id > 1", unless = "#id > 5" )
Copy the code

Sync: whether to use asynchrony is not mentioned

Take @cacheable as an example to see how caching works

Click me to study how SpringBoot cache works and how @cacheable works

@cachePUT Updates data and caches the results

Case 1:1. Query employee no. 1 and put the query result into the cache. 2.

// controller
/ * * *@author xiaozheng
 * @version 1.0
 * @date2020/11/24 14:48 * /
/ * * *@author xiaozheng
 * @version 1.0
 * @date2020/11/24 14:48 * /
@RestController
@RequestMapping("/emp")
public class EmployeeController {
	@Autowired
	private EmployeeService employeeService;
	@RequestMapping("/get/{id}")
	public Employee get(@PathVariable("id") Integer id){
		return employeeService.get(id);
	}


	@RequestMapping("/update")
	public Employee update(Integer id, String lastName, Integer geneder, String email){
		Employee employee = new Employee();
		employee.setLastName(lastName);
		employee.setId(id);
		employee.setEmail(email);
		employee.setGender(geneder);
		returnemployeeService.update(employee); }}Copy the code
// service
/ * * *@author xiaozheng
 * @version 1.0
 * @date 2020/11/24 14:50
 */
@Service
public class EmployeeService {
	@Autowired
	private EmployeeMapper employeeMapper;

	// If the query id is greater than 1 and the id is less than 5, the cache will be cached
	@Cacheable(cacheNames = {"emp"})
	public Employee get(Integer id){
		return employeeMapper.selectById(id);
	}


	@CachePut(cacheNames = {"emp"})
	public Employee update(Employee employee){
		employeeMapper.updateById(employee);
		returnemployee; }}Copy the code

\color{red}; \color{red} \color{red};

@CachePut(value = {"emp"}, key="#result.id")
Copy the code
http://localhost:8080/emp/get/1
http://localhost:8080/emp/update? id=1&lastName=2&geneder=150&email=1
Copy the code

To switch operations, change controller to:

@RequestMapping("/update")
	public Employee update(Integer id, String lastName, Integer geneder, String email){
		Employee employee = employeeService.get(id);
		employee.setLastName(lastName);
		employee.setId(id);
		employee.setEmail(email);
		employee.setGender(geneder);
		return employeeService.update(employee);
	}
Copy the code

Go to the cache first, and then update, it will update the cache synchronously, you can try it

@cacheevict Request caching

@cacheevict Annotation attribute description

Value and cacheName Specifies the cache component key: specifies the key to remove allEntries: Request all cache data in the cache component beforeInvocation: Specifies whether the cache is cleared before the method. The default value is false. If the method executes abnormally, the cache is not cleared

* /@RestController
@RequestMapping("/emp")
public class EmployeeController {
	@Autowired
	private EmployeeService employeeService;
	@RequestMapping("/get/{id}")
	public Employee get(@PathVariable("id") Integer id){
		return employeeService.get(id);
	}

	@RequestMapping("/delete/{id}")
	public Integer delete(@PathVariable("id") Integer id){
		 employeeService.delete(id);
		return id;
	}



	@RequestMapping("/update")
	public Employee update(Integer id, String lastName, Integer geneder, String email){
		Employee employee = employeeService.get(id);
		employee.setLastName(lastName);
		employee.setId(id);
		employee.setEmail(email);
		employee.setGender(geneder);
		returnemployeeService.update(employee); }}Copy the code
/ * * *@author xiaozheng
 * @version 1.0
 * @date 2020/11/24 14:50
 */
@Service
public class EmployeeService {
	@Autowired
	private EmployeeMapper employeeMapper;

	// If the query id is greater than 1 and the id is less than 5, the cache will be cached
	@Cacheable(value = {"emp"})
	public Employee get(Integer id){
		return employeeMapper.selectById(id);
	}


	@CachePut(value = {"emp"}, key="#result.id")
	public Employee update(Employee employee){
		employeeMapper.updateById(employee);
		return employee;
	}

	@CacheEvict(value = {"emp"})
	public void delete(Integer id){
		System.out.println("Delete s data"); }}Copy the code

Core code:

@CacheEvict(value = {"emp"})
Copy the code

Case 2:

	@CacheEvict(value = {"emp"}, allEntries = true)
Copy the code

Case 3:

@CacheEvict(value = {"emp"}, allEntries = true, beforeInvocation = true)
	public void delete(Integer id){
		System.out.println("Delete s data");
		int i = 10 / 0 ;
	}
Copy the code

@ Caching annotations

This annotation can be used when a method has a complex cache rule ratio

 // @caching Defines complex Caching rules
    @Caching( cacheable = { @Cacheable(/*value="emp",*/key = "#lastName") }, put = { @CachePut(/*value="emp",*/key = "#result.id"), @CachePut(/*value="emp",*/key = "#result.email") } )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }
Copy the code