reactive-programming - 从 Springboot + Webflux 中发出并行请求
问题描述
我正在使用带有 webflux 堆栈的 Springboot 2。
在应用程序中,我希望向下游服务并行发出多个 HTTP 请求,以减少返回客户端的总体响应时间。如果不玩线程,这可能吗?
我目前正在使用org.springframework.web.reactive.function.client.WebClient
但对支持此功能的其他客户开放;甚至是 RXJava。
解决方案
我设法通过以下方式实现了它。这是一个天真的例子,但是 async/http 请求是在downstream.request1()
和中发出的downstream.request2()
。如果是一种更优雅的方式来实现这一点,我会感兴趣。
@GetMapping("/sample")
public Mono<String> getMultipleRequests() {
Mono<String> monoResponse1 = downstream.request1();
Mono<String> monoResponse2 = downstream.request2();
return Mono.zip(monoResponse1, monoResponse2)
.flatMap(a -> myTransform(a));
}
private Mono<String> myTransform(Tuple2<String, String> tuple) {
String t1 = tuple.getT1();
String t2 = tuple.getT2();
return Mono.just(t1 + t2);
}
推荐阅读
- ios - Cordova iOS 通用链接问题
- java - 使用和公开 REST 服务并传递 JSON 正文
- amazon-web-services - AWS Cognito 密码过期
- javascript - 如何在不将 HTML 元素包装在 Javascript 中的情况下将第一个单词包装在字符串中?
- node.js - node.js Socket传输重叠
- javascript - 无法使用 node.js 保存到 mongodb
- mysql - percona 的 pt-achive 占用了过多的 CPU 和数据库连接
- swift - 如何使用 Codable 处理这种 JSON 格式
- php - InnoDB 在事务提交时重复插入
- flutter - 如何在颤动中创建布局