使用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;
}
相关推荐
看到请催我学习17 分钟前
内存缓存和硬盘缓存
开发语言·前端·javascript·vue.js·缓存·ecmascript
qq_51583806 彩雷王2 小时前
1004-05,使用workflow对象创建http任务,redis任务
redis·网络协议·http
Wang's Blog2 小时前
Redis: Sentinel节点管理,故障迁移一致性以及TILT模式
redis·sentinel
九圣残炎3 小时前
【springboot】简易模块化开发项目整合Redis
spring boot·redis·后端
小登ai学习4 小时前
简单认识 redis -3 -其他命令
数据库·redis·缓存
猿小蔡-Cool4 小时前
CPU 多级缓存
java·spring·缓存
BergerLee17 小时前
对不经常变动的数据集合添加Redis缓存
数据库·redis·缓存
Dylanioucn17 小时前
【分布式微服务云原生】掌握分布式缓存:Redis与Memcached的深入解析与实战指南
分布式·缓存·云原生
huapiaoy17 小时前
Redis中数据类型的使用(hash和list)
redis·算法·哈希算法
【D'accumulation】18 小时前
令牌主动失效机制范例(利用redis)注释分析
java·spring boot·redis·后端