(1) Reduce the pressure of frequently reading the database
(2) Some temporary data, such as SMS verification codes that will become invalid within 5 minutes, do not need to be stored in the database, and can be implemented in the cache.
Spring has defined Cache and CacheManager interfaces to unify different caching technologies since 3.1, and supports JCache (JSR-
107) Annotations to simplify our development
Some basic annotation concepts of caching are shown in the figure:
Cache, CacheManager, @Cacheable, @CacheEvict, @CachePut, @EnableCachsing, as shown below:
For example, the @Cacheable annotation is declared in front of the function, and if the query condition of the function has been executed before, the data will be fetched from the cache.
@CacheEvict is used to clear the cache, this can be declared in front of the delete(), update() methods
@CachePut: Used to update the cache, this annotation not only ensures that the method is called, but also ensures that the data can be put into the cache
Use MyBatis annotation version to connect to and operate MySQL database
Step 1: Add a new project including cache, Web, and MySQL launcher
Step 2: Configure the project property data source. The parameter after the database name is to avoid SQL garbled errors when connecting:
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_cache_demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Open hump naming convention matching rules
mybatis.configuration.map-underscore-to-camel-case=true
# Specify a package under the category of log level
logging.level.com.stephanie.cache.mapper=debug
Step 3: Customize the package path for scanning mapper, pay attention to the annotation @MapperScan:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
* Build a basic environment for cache development demo
* 1. Create a database, test the table department , employee , my local database name is spring_boot_cache_demo
* 2. Create Java Bean entity objects
* 3. Integrate MyBatis operation database
* ( 1 ) Configure data source information
* ( 2 ) Use annotated version of MyBatis
* ( A ) @MapperScan specifies the package path of all mapper packages that MyBatis needs to scan , and each scanned class needs to be annotated @Mapper
@MapperScan("com.stephanie.cache.mapper")
public class SpringBootDemoforCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoforCacheApplication.class, args);
Step 4: Write the Mapper interface class, pay attention to the annotation @Mapper
package com.stephanie.cache.mapper ;
import com.stephanie.cache.bean.Employee;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
public interface EmployeeMapper {
@Select("SELECT * FROM employee WHERE id = #{id}")
public Employee getEmpById (Integer id) ;
@Update("update employee set lastName=#{lastName}," +
"email=#{email}, gender=#{gender} WHERE id = #{id}")
public void updateEmp(Integer id);
@Delete("delete FROM employee WHERE id = #{id}")
public void deleteEmpById(Integer id);
@Insert("insert into employee(lastName,email,gender,dId) " +
" values(#{lastName}, #{email}, #{gender}, #{dId})")
public void insertEmp(Integer id);
The fifth step is to write the Service layer, pay attention to the @Service annotation:
package com.stephanie.cache.service;
import com.stephanie.cache.bean.Employee;
import com.stephanie.cache.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.xml.ws.ServiceMode;
public class EmployeeService {
// Adding @Autowired this annotation for the first time may report an error, you need to modify the error level
EmployeeMapper employeeMapper;
Employee employee = employeeMapper.getEmpById(1);
System.out.println("start emp="+employee.getStr()+"@");
Step 6: Write a test class to test the query SQL:
package com.stephanie.cache.controller;
import com.stephanie.cache.bean.Employee;
import com.stephanie.cache.mapper.EmployeeMapper;
import com.stephanie.cache.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
public class EmployeeController {
EmployeeService employeeService;
return employeeService.employee();
Operation effect, as shown below:
OK ! After the basic environment is ready, start simple cache learning!
The first step: specify to open the cache in the startup class:
* 1. Turn on annotation-based caching
* 2. Just mark the cache comment
// Enable annotation-based caching
@MapperScan("com.stephanie.cache.mapper")
public class SpringBootDemoforCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoforCacheApplication.class, args);
Step 2: Implement the specific method of caching in the Service business layer , that is, when you use this method to query data, you have the opportunity to fetch the data from the cache (when the employee data with the same id is queried multiple times, and the cache is used, it will not There is any log display. That is: the request log and mybatis query log are only available when the first query or cached data is empty.)
* Service layer test cache interface
* Several attributes of the cache :
* (1)cacheNames/value: Specify the name of the cache to distinguish which type of cache data is
* (2) key: The key used for the cached data , which can be used to specify, the default is to use the value of the method parameter, and each cache component has its own unique name .
*The following key="#id" indicates the value of the parameter id , #a0, #a1.. You can specify other fields as the primary key of the cache!
* (3)keyGenerator : key generator, you can specify your own key generator
* Key or keyGenerator second election use
* (4)cacheManager : Specify a cache manager, or cacheResolver to specify a resolver
* (5)condition : Specifies that the cache will only work under certain conditions
* (6)unless: Negative caching, that is: if a certain condition is met, the data will not be cached . For the writing of the condition, you can also take the query result to write the condition
@Cacheable(cacheNames = "employee", key="#id",condition="#id>0")
public Employee getEmpfromCache(Integer id)
System. out .println( " Query employee information with id=" +id+ " :" ) ;
Employee emp = employeeMapper .getEmpById (id) ;
In addition, the specific supplementary description of the key:
Cacheable annotated parameter key value can specify the matching item keyword. The default common usage is key="#id". The most common use of this table id to identify data, other ways to specify keys are as follows:
How the cache works: (I lost my mind when watching this paragraph...)
(1) Cache automatic configuration class: CacheAutoConfiguration
(2) Cached configuration class
(3) Which configuration class takes effect: SImpleCacheConfiguration
(4) Register a CacheManager and ConcurrentMapCacheManager in the container
(5) Can obtain and create ConcurrentMapCache type cache components, the role is to data
@Cacheable annotation running process:
(1) Query the cache component Cache and obtain it according to the name specified by cacheNames. The first time to get the cache, if there is no cache component, create a Cache component;
(2) Go to the Cache to find the cache, use a key, the default key is the parameter of the method;
(3) Call the target query method if the cache is not found
(4) Put the result returned by the target method into the cache