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();
    }
相关推荐
IT_陈寒20 分钟前
Vue的响应式竟然在这常见操作下失效了
前端·人工智能·后端
她说彩礼65万29 分钟前
Asp.net core ContenResult
后端·asp.net
程序猿DD32 分钟前
国内模型供应商缓存与可用性实测:谁更适合跑 Agent?
人工智能·缓存·agent
砍材农夫44 分钟前
redis|spring-boot redis geo|附近定位功能
java·spring boot·redis
草莓熊Lotso1 小时前
【Redis 初阶】 从分布式演进背景到环境搭建全解析
数据库·人工智能·redis·分布式·缓存
AI-好学者1 小时前
Redis高可用与分布式架构
redis·分布式·缓存·架构
枕星而眠1 小时前
Git仓库基础用法
大数据·git·后端·elasticsearch·全文检索
ayqy贾杰1 小时前
Claude Fable 5 提示词泄漏,抓紧学习下
前端·后端·面试
智码看视界1 小时前
Day18 SpringBoot自动配置原理:从@SpringBootApplication开始
java·spring boot·后端·自动装配
程序员爱钓鱼2 小时前
Rust 常量与静态变量详解:const 与 static 的区别
后端