使用SpringCache操作Redis缓存数据

SpringCache概念

SpringCache是一个框架,实现了基于注解的缓存功能,只需要简单的加一个注解,就能实现缓存功能。

SpringCache提供了一层抽象,底层可以切换不同的缓存实现,例如:

  • EHCache
  • Caffeine
  • Redis

使用(导入redis跟SpringCache的 依赖即可)

复制代码
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

SpringCache常用注解

|----------------|------------------------------------------------------------|
| @EnableCaching | 开启缓存注解功能,加在启动类上 |
| @Cacheable | 加在方法上,执行方法前会先去缓存中查看是否有缓存有的话直接返回,没有的话会通过反射调用方法,并将方法的返回值缓存起来 |
| @CachPut | 将方法的返回值,直接放在缓存中 |
| @CacheEvict | 将一条数据或者多条数据从缓存中删除 |

@Cacheable使用

复制代码
@GetMapping("/test")
@Cacheable(value = "test",key = "#key",unless = "#result == null") //组合起来的key就是test:: + 入参key
public String test(String key) {
return "hello SpringCache";
}

如果入参是对象:

复制代码
@GetMapping("/test")
@Cacheable(value = "test",key = "#user.id",unless = "#result == null") //组合起来的key就是test:: + 入参user的id属性
public String test(User user) {
return "hello SpringCache";
}

unless

unless的意思就是: 当不满足条件的时候进行缓存 也就是condition 相反,因为condition中没有#result这个spel表达式,所以要使用unless

底层知识:

Cacheable底层是通过代理来实现的,当你调用的时候创建一个Controller的代理对象,会先拼接key,判断在缓存中是否存在,存在直接返回,不存在通过反射调用方法。如果返回值满足指定条件(condition、unless)会将返回值缓存起来。

@CachePut 使用

CachePut会将返回值放到缓存中,unless跟condition跟Cacheable一样

还有一个不同就是Cacheable的key没有#result这个表达式,CachePut有

可以看一下CachePut源码的注释:

复制代码
@GetMapping("/test3")
@CachePut(value = "test3",key = "#key")
public List<String > test3(String key) {
List<String > list = new ArrayList<>();
list.add("1");
list.add("1");
list.add("1");
list.add("1");
return list;
}

@CacheEvict 使用

精准删除(test4::key)

复制代码
@GetMapping("/test4")
@CacheEvict(value = "test4",key = "#key")
public List<String > test4(String key) {
return null;
}

全部删除(test4::)

复制代码
@GetMapping("/test4")
@CacheEvict(value = "test4",allEntries = true)
public List<String > test4(String key) {
return null;
}
相关推荐
麦兜*15 小时前
Redis内存消耗异常飙升?深入排查与Big Key/Hot Key的根治方案
jvm·数据库·spring boot·redis·spring·缓存
成为你的宁宁16 小时前
【Redis 从入门到实战:详细讲解 Redis 安装配置、RDB/AOF 数据持久化方案、一主两从同步部署,深入剖析哨兵模式工作原理与哨兵模式高可用全攻略】
数据库·redis·缓存
ifeng091816 小时前
HarmonyOS网络请求优化实战:智能缓存、批量处理与竞态处理
网络·缓存·harmonyos
5***o50016 小时前
前端构建工具缓存清理,解决依赖问题
前端·缓存
v***56516 小时前
使用bitnamiredis-sentinel部署Redis 哨兵模式
数据库·redis·sentinel
一叶飘零_sweeeet20 小时前
2025 年 Redis 面试天花板
redis·缓存·面试
d***93521 小时前
Redis五种用途
数据库·redis·缓存
爬山算法1 天前
Redis(128)Redis的跳表(Skip List)是如何实现的?
数据库·redis·list
Unstoppable221 天前
八股训练营第 20 天 | MySQL和Redis的区别是什么?Redis有什么优缺点、为什么用Redis查询会比较快?
数据库·redis·mysql·八股
e***74951 天前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python