Spring boot + Redis + Spring Cache 实现缓存

学习

Redis 的 value 有 5 种常用的数据结构

Redis 存储的是 key-value 结构的数据。key 是字符串类型,value 有 5 种常用的数据结构:

Redis 的图形化工具

Another Redis Desktop Manager

Spring Data Redis

Redis 的 Java 客户端。

Spring Cache

Spring Cache 是一个框架,基于注解实现缓存功能,更加简单。底层的缓存实现,可以是Redis、Caffeine或者EHCache等。

Spring Cache 常用注解:

配置

  1. 下载Redis。(默认没有密码)
  2. 在 xml 中引入 Spring Data Redis 和 Spring Cache 2.7.3 的依赖。
  3. 在 yml 中配置 Redis 数据源。

实现

1. 开启:@EnableCaching

放在启动类上,开启缓存注解功能。

2. 增:@CachePut

在 Controller 层:

java 复制代码
//    增
    @PostMapping()
    @CachePut(cacheNames = "userCache", key = "#user.id")  // key = userCache::id
    public User save(@RequestBody User user) throws IOException {
//        保存到mysql
        userService.save(user);
//        保存到mysql后,id已经有了,可以直接插入到ES
        esService.AddDocument(user);
        return user;
    }

采用了spEL表达式(#对象.属性)。

注:先操作 save 方法,再操作 @CachePut,所以 user 此时有 id 了。

3. 查:@Cacheable

4. 删、改:@CacheEvict

  1. @CacheEvict(cacheNames = "userCache", key = "#user.id") 删除某个id
  2. @CacheEvict(cacheNames = "userCache", allEntries = True) 删除所有
相关推荐
meiying883815 分钟前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化
@大迁世界1 小时前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper1 小时前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
南归北隐1 小时前
Spring AI Alibaba Graph框架实现MCP数据库查询实战
java·后端·spring ai·mcp·spring ai mcp
学逆向的1 小时前
C 指针常量与常量指针
c语言·开发语言·网络安全
古法老登瞎折腾1 小时前
大数据智能运维实战(九):让 AI 查日志——找到异常,也保留上下文
java·大数据·运维·人工智能·spring ai·mcp
ai大模型-探索者1 小时前
Function Call与MCP(区别、联系与实战)
java·服务器·网络
略略略咯咯1 小时前
啊啊啊啊啊
java·服务器·数据库
SL_staff2 小时前
运维救火实战:钉钉API变更致薪资计算中断,如何用可视化逻辑引擎5分钟热修复
java·开源·全栈
低调滴开发2 小时前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust