springBoot caching mechanism cache

1. Introduce cache

When creating the project at the beginning, be sure to check the cache item (the front is the basic operation, select spring Initializr, the default option, then check the cache, and the others are checked according to the project needs)
Write picture description here

2. Prepare the environment in advance

Write picture description here
The entire directory is shown in the figure:
Write picture description here
Department class

package com.zyj.springboot_cache.bean;

public class Department {
    
    
    private Integer id;
    private String departMentName;

    public Department(Integer id, String departMentName) {
        this.id = id;
        this.departMentName = departMentName;
    }

    public Department() {
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", departMentName='" + departMentName + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartMentName() {
        return departMentName;
    }

    public void setDepartMentName(String departMentName) {
        this.departMentName = departMentName;
    }
}

employee class

package com.zyj.springboot_cache.bean;

public class Employee {
    
    
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;
    private Integer dId;

    public Employee() {
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", dId=" + dId +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Integer getdId() {
        return dId;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }

    public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.dId = dId;
    }
}

EmployeeController:

package com.zyj.springboot_cache.controller;

import com.zyj.springboot_cache.bean.Employee;
import com.zyj.springboot_cache.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    @GetMapping("/emp/{id}")
    @ResponseBody
    public Employee getEmpById(@PathVariable("id") Integer id) {
        Employee empById = employeeService.getEmpById(id);
        return empById;
    }

    @ResponseBody
    @GetMapping("/updateEmp")
    public Employee updateEmp(Employee employee) {
        System.out.println("方法执行。。。。");
        Employee employee1 = employeeService.updateEmp(employee);
        return employee1;
    }

    @RequestMapping("/delemp")
    public String delEmp(Integer id) {
        employeeService.del(id);
        return "success";
    }

    @RequestMapping("/emp/getEmpByLastName/{lastName}")
    @ResponseBody
    public Employee getEmpByLastName(@PathVariable(value = "lastName") String lastName) {
        System.out.println(lastName);
        return employeeService.getEmpByLastName(lastName);
    }
}

EmployeeMapper

package com.zyj.springboot_cache.mapper;

import com.zyj.springboot_cache.bean.Employee;
import org.apache.ibatis.annotations.*;

@Mapper
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},dId = #{dId} where id=#{id}")
    public void updateEmp(Employee employee);

    @Delete("DELETE FROM employee WHERE id = #{id}")
    public void deleteEmp(Employee employee);

    @Insert("INSERT INTO employee (lastName,email,gender,dId) VALUES(#{lastName},#{email},#{gender},#{dId})")
    public void insertEmp(Employee employee);

    @Select("SELECT * FROM employee WHERE lastName = #{lastName}")
    Employee getEmpByLastName(String lastName);
}

Write picture description here
Example: Take the above exercise as an example:
1. Get employee information through employee id ( @Cacheable )

   @Cacheable(cacheNames = {
   
   "emp"})
    public Employee getEmpById(Integer id) {
        System.out.println("查询" + id + "号员工!");
        Employee empById = employeeMapper.getEmpById(id);
        return empById;
    }

After querying once, you will see the output of the query in the console. The second time you query, the console does not output the log output of the query, which means that this is taken from the cache and the database is not queried.
2. Update employee information ( @Cacheput )

 @CachePut(value = "emp", key = "#result.id")
    public Employee updateEmp(Employee employee) {
        System.out.println("updateEmployee:" + employee);
        employeeMapper.updateEmp(employee);
        System.out.println(employee);
        return employee;
    }

Note that there is key = "#result.id" , if it is not added, it will also cache, but it is not the same key as the data in the cache just now, so when we query again, the query is still in the cache before The old data has not been updated, so the key addition is consistent with the data stored just now, ensuring that the data is the same as the data in the database.
3. Clear the cache ( @CacheEvict )

 @CacheEvict(value = "emp")
    public void del(Integer id) {
        System.out.println("删除id为" + id + "的员工");
   }

(1) First query the data with employee number 1. The console prints the query information, and then performs the query again. The console does not print information, indicating that it has been cached.
(2) At this time, the data is cleared, and the employee is deleted (just print out)
(3) If you query again, you will see that the database is queried again, which proves that the data just now has been cleared
4. @Caching

 @Caching(
            cacheable = {
                    @Cacheable(key = "#lastName")
            },
            put = {
                    @CachePut(key = "#result.id"),
                    @CachePut(key = "#result.email")
            }
    )
    public Employee getEmpByLastName(String lastName) {
        return employeeMapper.getEmpByLastName(lastName);
    }

(1) Combination: send request

http://localhost:8080//emp/getEmpByLastName/zhangsan

You can see the console output
(2) At this time, the cache has been carried out, and the query operation is performed again

http://localhost:8080//emp/1

(3) It can be seen that the console did not output again, indicating that it has been cached at this time, and proceed again:

http://localhost:8080//getEmpByEmail/123456

(4) The console did not output again, indicating that the cache is effective

Thanks for the explanation from the teacher of Shang Silicon Valley Video at Grain Academy! ! !

Guess you like

Origin blog.csdn.net/qiuqiu1628480502/article/details/81427630