引入依赖 spring-boot-starter-cache (springboot内置缓存解决方案)

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

开启缓存 启动类中加入@EnableCaching

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;


/**
 * @author sheep669
 * "@EnableCaching 开启缓存功能"
 */
@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

使用 @Cacheable

    @Cacheable(cacheNames = "student",key = "#id")
    @Override
    public Student getStudentById(Integer id) {
        return studentDAO.selectById(id);
    }

数据库里,相同sql请求,在缓存中读取,不再进入数据库操作。

condition condition = "#id>4" 表示id大于4的进缓存 key = "#id" 表示参数 cacheNames = "student" 缓存名

@Cacheable(cacheNames = "student", key = "#id", condition = "#id>4")

key 的其他写法

key = "#id" //参数
key = "#result.id" //返回结果的id
key = "#args[0]"   //多参数的第一个参数

cacheNames = "student", key = "#id" 查询和更新需要一致,更新才能生效

    @CachePut(cacheNames = "student", key = "#result.id")
    @Override
    public Student updateStudent(Student student) {
        studentDAO.updateById(student);
        return student;
    }

    @Cacheable(cacheNames = "student", key = "#id")
    @Override
    public Student getStudentById(Integer id) {
        return studentDAO.selectById(id);
    }

不一致的情况下,更新后,查询仍会从缓存获取数据,而不是更新后的数据

不同操作有对应的注解

//删除
    @CacheEvict(cacheNames = "student", beforeInvocation = true)
    @Override
    public int delStudent(Integer id) {
        return studentDAO.deleteById(id);
    }
//修改,添加
    @CachePut(cacheNames = "student", key = "#result.id")
    @Override
    public Student updateStudent(Student student) {
        studentDAO.updateById(student);
        return student;
    }
//查询
    @Cacheable(cacheNames = "student", key = "#id")
    @Override
    public Student getStudentById(Integer id) {
        return studentDAO.selectById(id);
    }

简化写法 @CacheConfig(cacheNames = "student") 写在类上 提出公共的cacheNames