springboot+Cache

一:緩存

1.導入需要依賴

core:Cache

web:web

Sql:mysql+Mybatis

2.搭建基本環境

創建數據庫
Student(學生表)
   id        int          主鍵:自增
   name      varchar(20)  姓名
   gender    bit          性別(true:女   false:男)
   grade_id  int          外鍵(年級編號)

Grade(年級表)
id        int          主鍵:自增
name      varchar(20)  年級名次

3.創建javaBean(POJO)

@Data
public class Student {
    private Integer id;
    private String name;
    private Boolean gender;
    private Integer gradeId;
}


@Data
public class Grade {
    private Integer id;
    private String name;
}

4.整和mybatis

4.1  application.properties

#dataSource

#spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis

spring.datasource.username=root

spring.datasource.password=root


#mybatis配置(開啓駝峯命名)
mybatis.configuration.map-underscore-to-camel-case=true

4.2 mapper層編碼

@Mapper
public interface StudentMapper {
    /**
     * 根據id獲取到對象
     * @param id    學生編號
     * @return      學生對象
     */
    @Select("select * from student where id=#{id}")
    Student getStudentById(Integer id);
}

5.編碼controller

@RestController
public class StudentContorller {

    @Autowired
    private StudentMapper studentMapper;
    @RequestMapping("/getById/{stuid}")
    public Student getById(@PathVariable("stuid") int stuid){

        return studentMapper.getStudentById(stuid);
    }
}

6.緩存

6.1緩存所需要的註解--開啓應用緩存

/*
        將數據放入到緩存中
            cacheNames/value:指定緩存組件的名字
            key:緩存數據使用的key,默認參數是方法的返回值
                #root.methodName        被調用的方法名
                #root.method.name       當前被調用的方法
                #root.target            被調用的目標對象
                #root.targetClass       被大哦有那個的目標對象類
                #root.args[0]           被調用的方法的參數列表
             keyGenerator:key的生成器,默認是主鍵id(和key是二選一)
             cacheManager:指定緩存管理器(比如redis)
     */
    @Cacheable(cacheNames="stu",key = "#root.args[0]")
    @Override
    public Student getStudentById(Integer stuid) {
        return studentMapper.getStudentById(stuid);
    }

6.2修改緩存中數據

 @CachePut

6.3清楚緩存

@CacheEvict

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章