springboot中使用springboot cache

前言:SpringBoot中使用Cache缓存可以提高对缓存的开发效率

此图片是SpringBootCache常用注解
Springboot Cache中常用注解

第一步:引入依赖

XML 复制代码
        <!--缓存-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

第二步:在启动类添加@EnableCachin

XML 复制代码
@EnableCaching    //开启缓存注解功能

第三步:在实体类上继承序列化接口

XML 复制代码
public class User implements Serializable 

第四步:使用注解

java 复制代码
    @PostMapping("/add")
    @CachePut(cacheNames = "userCache",key = "#user.id")   //缓存数据
    public User addInfo(@RequestBody User user){
        boolean save = userService.save(user);
        return user;
    }

    @GetMapping("/get/{id}")
    @Cacheable(cacheNames = "userCache", key = "#id")     //查询redis中是否存储的有数据,有数据直接返回,没有数据前往MySQL查询数据
    public User getUser(@PathVariable Integer id){
        return userService.getById(id);
    }

    @DeleteMapping("/del/{id}")
    @CacheEvict(cacheNames = "userCache",key = "#id")    //删除数据的时候同时删除缓存数据
    public void delUser(@PathVariable Integer id){
        userService.removeById(id);
    }

    @DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries = true)    //删除全部数据的时候同时删除缓存中全部数据
    public void delUser(){
        userService.deleteAll();
    }
相关推荐
Penge6662 小时前
Go 接口编译期断言
后端
我是一颗柠檬2 小时前
【MySQL全面教学】MySQL面试高频考点汇总Day15(2026年)
数据库·后端·mysql·面试
拽着尾巴的鱼儿3 小时前
springboot openfeign 自定义feign 接口重试机制
java·spring boot·后端
Ceelog3 小时前
久坐党自救指南:屏幕前 8 小时,身体到底在经历什么
前端·后端
XS0301064 小时前
并发编程 六
java·后端
小饼干在学嘎瓦4 小时前
本地缓存和分布式缓存如何选择?
分布式·缓存
雪宫街道4 小时前
synchronized 锁的范围:对象锁、类锁与代码块锁
java·jvm·后端·面试
XS0301065 小时前
Spring Bean 作用域 & 生命周期
java·后端·spring
彦为君5 小时前
JavaSE-07-异常机制
java·开发语言·后端·python·spring