使用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;
}
相关推荐
BduL OWED5 小时前
Redis之Redis事务
java·数据库·redis
Zzxy6 小时前
Redis集成与基础操作
spring boot·redis
尽兴-7 小时前
Elasticsearch 性能调优指南:写入、检索、聚合与缓存全链路优化
大数据·elasticsearch·缓存·性能优化·es 读写原理
amIZ AUSK7 小时前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
有毒的教程7 小时前
Ubuntu 清理 Docker 镜像 / 容器 / 缓存 完整教程
ubuntu·缓存·docker
青槿吖8 小时前
第一篇:Redis集群从入门到踩坑:3主3从保姆级搭建+核心原理一次性讲透|面试必看
前端·redis·后端·面试·职场和发展·bootstrap·html
zs宝来了9 小时前
Redis 网络模型:IO 多路复用与 ae 事件循环
redis·epoll·事件循环·io多路复用·网络模型
羊小猪~~9 小时前
Redis学习笔记(数据类型、持久化、事件、管道、发布订阅等)
开发语言·数据库·c++·redis·后端·学习·缓存
曲幽10 小时前
FastAPI + Celery 实战:异步任务里调用 Redis 和数据库的全解析,及生产级组织方案
redis·python·fastapi·web·async·celery·task·queue
tsyjjOvO11 小时前
Redis 从入门到集群搭建(续)
redis·后端·缓存