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();
    }
相关推荐
考虑考虑6 小时前
cmd局部设置java变量
运维·后端·自动化运维
陈随易9 小时前
在Finch用了62亿词元,我认为这是新一代Agent工具之神
前端·人工智能·后端
wing9810 小时前
从codex转战workbuddy使用一周的感受
前端·人工智能·后端
EatFan10 小时前
Java接入支付宝 JSAPI 支付保姆教程(二):流程讲解与前后端代码讲解
前端·spring boot·后端·微信小程序·小程序·uni-app
步行cgn11 小时前
Spring 报错:No bean class specified on bean definition 的原因与解决
java·后端·spring
凤山老林11 小时前
Spring Boot 整合 Flowable 的企业级落地指南
数据库·spring boot·后端·flowable·工作流
苏三说技术11 小时前
Kafka已正式接入AI
后端
企业数字化笔记11 小时前
AI写的系统出现504怎么办?接口超时和数据库慢查询排查
数据库·后端
IT_陈寒11 小时前
Redis的Set操作居然能把我的服务整挂了?
前端·人工智能·后端
玄芯散人11 小时前
【筑基·047】内存Hierarchy:寄存器到硬盘的速度差
缓存·内存·计算机基础