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_陈寒1 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
晨星shine2 小时前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
蝎子莱莱爱打怪2 小时前
OpenClaw 从零配置指南:接入飞书 + 常用命令 + 原理图解
java·后端·ai编程
倚栏听风雨3 小时前
【ES避坑指南】明明存的是 "CodingAddress",为什么 term 查询死活查不到?彻底搞懂 text 和 keyword
后端
程序员爱钓鱼3 小时前
Go 操作 Windows COM 自动化实战:深入解析 go-ole
后端·go·排序算法
回家路上绕了弯3 小时前
深入解析Agent Subagent架构:原理、协同逻辑与实战落地指南
分布式·后端
子玖3 小时前
实现微信扫码注册登录-基于参数二维码
后端·微信·go
IT_陈寒3 小时前
JavaScript代码效率提升50%?这5个优化技巧你必须知道!
前端·人工智能·后端
IT_陈寒3 小时前
Java开发必知的5个性能优化黑科技,提升50%效率不是梦!
前端·人工智能·后端
东风t西瓜4 小时前
飞书项目与多维表格双向同步
后端