「Spring Reactive Stack」响应式方式访问Redis

Spring Data Redis中同时支持了Jedis客户端和Lettuce客户端。但是仅Lettuce是支持Reactive方式的操作;这里选择默认的Lettuce客户端。

  1. 创建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>
  2. 配置文件application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    spring:
    redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
    #Redis数据库索引(默认为0)
    database: 0
    #连接超时时间(毫秒)
    timeout: 5000
  3. 注入配置类:

    1
    2
    3
    4
    5
    6
    7
    @Configuration
    public class ReactiveRedisConfig {
    @Bean
    public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
    return new ReactiveRedisTemplate<>(factory, RedisSerializationContext.string());
    }
    }
  4. 简单的RedisService封装

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    @Service
    @AllArgsConstructor
    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);
    }
    }
  5. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @SpringBootTest
    class ReactiveRedisTest {
    @Resource
    private RedisService redisService;

    @Test
    void test1() {
    // 保存5分钟
    redisService.set("test1", "test1_value", 5 * 60L).subscribe(System.out::println);
    redisService.get("test1").subscribe(System.out::println);
    }
    }

测试运行结果:

1
2
true
test1_value

本文使用Spring Boot版本:2.4.3