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();
    }
相关推荐
学长毕设8 小时前
基于SpringBoot的儿童慈善捐赠管理系统-附源码
java·spring boot·后端
皮皮林5519 小时前
GitHub Copilot:你可以暂时不用,但别不知道它有多强
后端
学长毕设9 小时前
基于SpringBoot非遗文化展示与传播平台设计与实现-附源码
java·spring boot·后端
杨凯凡10 小时前
Spring Boot SSE 上线后不实时、频繁断线?Nginx 缓冲、心跳与连接回收实战
spring boot·后端·nginx
锋行天下11 小时前
langgraph 全栈项目(三)
前端·人工智能·后端
金銀銅鐵11 小时前
用 Swing 重做操作数栈演示
java·jvm·后端
锋行天下12 小时前
langgraph 全栈项目(二)
前端·人工智能·后端
Flynn Liang12 小时前
大模型成本优化:基于 Redis 的可验证语义缓存架构
人工智能·redis·缓存·架构·ai agent·智能体
锋行天下12 小时前
langgraph全栈项目(一)
前端·人工智能·后端
学长毕设13 小时前
基于SpringBoot的游戏攻略社区交流系统-附源码
spring boot·后端·游戏