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();
    }
相关推荐
码事漫谈5 小时前
C++ 多线程开发:从零开始的完整指南
后端
9ilk5 小时前
【C++】--- 特殊类设计
开发语言·c++·后端
码事漫谈5 小时前
十字路口的抉择:B端与C端C++开发者的职业路径全解析
后端
提笔了无痕7 小时前
git基本了解、常用基本命令与使用
git·后端
unique_perfect7 小时前
vue2与springboot实现deepseek打印机聊天
spring boot·websocket·ai·vue2·deepseek
java1234_小锋7 小时前
Spring IoC的实现机制是什么?
java·后端·spring
喵个咪7 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:JWT 集成指南
后端·go
绝不收费—免费看不了了联系我7 小时前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
喵个咪8 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:OPA 集成指南:从原理到实践
后端·go
哈哈老师啊8 小时前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot