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) 删除所有
相关推荐
小信丶8 小时前
Spring Cloud Stream EnableBinding注解详解:定义、应用场景与示例代码
java·spring boot·后端·spring
无限进步_8 小时前
【C++】验证回文字符串:高效算法详解与优化
java·开发语言·c++·git·算法·github·visual studio
亚历克斯神8 小时前
Spring Cloud 2026 架构演进
java·spring·微服务
浅时光_c8 小时前
12 指针
c语言·开发语言
七夜zippoe8 小时前
Spring Cloud与Dubbo架构哲学对决
java·spring cloud·架构·dubbo·配置中心
海派程序猿8 小时前
Spring Cloud Config拉取配置过慢导致服务启动延迟的优化技巧
java
charlie1145141918 小时前
嵌入式现代C++工程实践——第10篇:HAL_GPIO_Init —— 把引脚配置告诉芯片的仪式
开发语言·c++·stm32·单片机·c
call me by ur name8 小时前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin
dog2508 小时前
细看高维空间中距离度量失效
开发语言·php
码云数智-大飞8 小时前
Rust的所有权模型如何消除内存安全问题?与C++的RAII有何异同?
开发语言