「学习笔记」Spring Reactive Stack(四)响应式方式访问Redis
Spring Data Redis中同时支持了Jedis客户端和Lettuce客户端。但是仅Lettuce是支持Reactive方式的操作;这里选择默认的Lettuce客户端。
- 创建
Maven项目,并在pom.xml导入依赖:
<!-- reactive redis依赖包(包含Lettuce客户端) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
- 配置文件
application.yml
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
#Redis数据库索引(默认为0)
database: 0
#连接超时时间(毫秒)
timeout: 5000
- 注入配置类:
@Configuration
public class ReactiveRedisConfig {
@Bean
public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
return new ReactiveRedisTemplate<>(factory, RedisSerializationContext.string());
}
}
- 简单的RedisService封装
@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);
}
}
- 测试
@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);
}
}
测试运行结果:
true
test1_value
本文使用Spring Boot版本:2.4.3
END .
相关系列文章
- 「学习笔记」SpringCloud(五)OpenFeign整合Sentinel实现熔断降级
- 「学习笔记」SpringCloud(四)OpenFeign服务间调用
- 「学习笔记」SpringCloud(三)Config配置中心
- 「学习笔记」SpringCloud(二)Gateway网关
- 「学习笔记」SpringCloud(一)Eureka注册中心
- 「学习笔记」Spring Reactive Stack(六)响应式 HTTP 请求客户端 WebClient
- 「学习笔记」Spring Reactive Stack(五)服务端事件推送Server-Sent Events
- 「学习笔记」Spring Reactive Stack(四)响应式方式访问Redis
- 「学习笔记」Spring Reactive Stack(三)使用R2DBC访问MySQL
- 「学习笔记」Spring Reactive Stack(二)Reactor异常处理
- 「学习笔记」Spring Reactive Stack(一)Spring WebFlux响应式Web框架入门
- 「工程实践」Spring Boot - 使用RocketMQ实战样例
- 「工程实践」RocketMQ安装并整合SpringBoot
- 「工程实践」Spring Boot + Thymeleaf页面静态化实现
- 「工程实践」Spring Boot - Java接口幂等性设计
- 「工程实践」Spring Boot 整合 FastDFS
- 「学习笔记」Spring Boot MVC 应用
- 「学习笔记」Spring Boot 数据库访问
- 「学习笔记」Spring Boot 入门
- 「学习笔记」Spring--SSM框架整合(Spring+SpringMVC+MyBatis)
- 「学习笔记」Spring--持久层框架Mybatis
- 「学习笔记」Spring--MVC框架
- 「学习笔记」Spring--面向切面编程(AOP模块)
- 「学习笔记」Spring--事务管理
- 「学习笔记」Spring--JDBC详解
- 「学习笔记」Spring--IoC注解实现
- 「学习笔记」Spring--IoC控制反转