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();
    }
相关推荐
屹奕26 分钟前
Arthas工具快速使用
spring boot·arthas
陈果然DeepVersion2 小时前
Java大厂面试真题:Spring Boot微服务+Kafka消息队列+AIGC场景实战问答全解析
spring boot·redis·微服务·kafka·消息队列·aigc·java面试
小妖同学学AI2 小时前
Rust 深度解析:基本类型的“精确”艺术
开发语言·后端·rust
我命由我123452 小时前
Guava - Guava 基本工具 Preconditions、Optional
java·服务器·开发语言·后端·java-ee·guava·后端框架
程序猿ZhangSir2 小时前
Spring Boot 项目实现邮件推送功能 (以QQ邮箱为例)
java·数据库·spring boot
Python私教2 小时前
Rust 快速入门:从零到上手的系统指南
开发语言·后端·rust
JosieBook2 小时前
【SpringBoot】30 核心功能 - 单元测试 - JUnit5 单元测试简介与常用注解实战详解
spring boot·后端·单元测试
cj6341181502 小时前
网卡驱动架构以及源码分析
java·后端
Sincerelyplz3 小时前
【JDK新特性】分代ZGC到底做了哪些优化?
java·jvm·后端
zs宝3 小时前
Java 限流简易实现
后端