Spring Data Redis
中同时支持了Jedis
客户端和Lettuce
客户端。但是仅Lettuce
是支持Reactive
方式的操作;这里选择默认的Lettuce
客户端。
创建
Maven
项目,并在pom.xml
导入依赖:1
2
3
4
5<!-- reactive redis依赖包(包含Lettuce客户端) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>配置文件
application.yml
1
2
3
4
5
6
7
8
9spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
#Redis数据库索引(默认为0)
database: 0
#连接超时时间(毫秒)
timeout: 5000注入配置类:
1
2
3
4
5
6
7
public class ReactiveRedisConfig {
public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
return new ReactiveRedisTemplate<>(factory, RedisSerializationContext.string());
}
}简单的RedisService封装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class RedisService {
private final ReactiveRedisTemplate<String, String> redisTemplate;
public Mono<String> get(String key) {
return key==null ? null : redisTemplate.opsForValue().get(key);
}
public Mono<Boolean> set(String key, String value) {
return redisTemplate.opsForValue().set(key, value);
}
public Mono<Boolean> set(String key, String value, Long time) {
return redisTemplate.opsForValue().set(key, value, Duration.ofSeconds(time));
}
public Mono<Boolean> exists(String key) {
return redisTemplate.hasKey(key);
}
public Mono<Long> remove(String key) {
return redisTemplate.delete(key);
}
}测试
1
2
3
4
5
6
7
8
9
10
11
12
class ReactiveRedisTest {
private RedisService redisService;
void test1() {
// 保存5分钟
redisService.set("test1", "test1_value", 5 * 60L).subscribe(System.out::println);
redisService.get("test1").subscribe(System.out::println);
}
}
测试运行结果:
1 | true |
本文使用Spring Boot版本:2.4.3
原文链接: http://chaooo.github.io/2021/03/04/spring-reactive-redis.html
版权声明: 转载请注明出处.