java - 使用 akka HTTP 调用多个 API
问题描述
我是 AKKA 的新手,我正在尝试触发 3 个请求,将每个请求的超时设置为 ~1 秒以完成,汇总结果。3 个请求或多个请求将是简单的 API 调用 GET,其中来自 API 的响应将以 JSON 格式。到目前为止我的代码
final ActorSystem system = ActorSystem.create();
final ActorMaterializer materializer = ActorMaterializer.create(system);
final Flow<HttpRequest, HttpResponse, CompletionStage<OutgoingConnection>> connectionFlow =
Http.get(system).outgoingConnection(toHost("https://example/api/ticker", 80));
final CompletionStage<HttpResponse> responseFuture =
Source.single(HttpRequest.create("/"))
.via(connectionFlow)
.runWith(Sink.<HttpResponse>head(), materializer).;
对此的任何帮助将不胜感激。
解决方案
我不太熟悉的java
版本,akka
所以下面的示例代码可能无法编译,但它展示了一般的想法......
大概您有将来自先前 API 调用的响应转换为对下一个 API 的请求的函数:
public static HttpRequest convertAPI1Response(HttpResponse httpResponse) {
}
public static HttpRequest convertAPI2Response(HttpResponse httpResponse) {
}
然后可以将这些转换器放置在Flow
值内:
final Flow<HttpResponse, HttpRequest, ...> convertAPI1Flow =
Flow.of(HttpResponse.class).map(convertAPI1Response)
final Flow<HttpResponse, HttpRequest, ...> convertAPI2Flow =
Flow.of(HttpResponse.class).map(convertAPI1Response)
这些流程现在可以与outgoingConnection
问题已经引用的流程一起使用:
final Flow<HttpRequest, HttpResponse, CompletionStage<OutgoingConnection>> connection1Flow =
Http.get(system).outgoingConnection(toHost("https://example/api/ticker", 80));
final Flow<HttpRequest, HttpResponse, CompletionStage<OutgoingConnection>> connection2Flow =
Http.get(system).outgoingConnection(toHost("https://someOtherHost.com/api", 80));
final Flow<HttpRequest, HttpResponse, CompletionStage<OutgoingConnection>> connection3Flow =
Http.get(system).outgoingConnection(toHost("https://someOtherOtherHost.com/api", 80));
最后,所有流都可以连接在一起:
final CompletionStage<HttpResponse> responseFuture =
Source.single(HttpRequest.create("/"))
.via(connection1Flow)
.via(convertAPI1Flow)
.via(connection2Flow)
.via(convertAPI2Flow)
.via(connection3Flow)
.runWith(Sink.<HttpResponse>head(), materializer).;
推荐阅读
- oracle - Oracle SQL Merge 查询修复数据完整性问题
- java - 从根节点到java中的点的某些点没有得到正确的路径
- excel - VBA下拉列表IFS公式
- ios - Swift UI:如果文本字段为空,则禁用按钮
- dataframe - 熊猫数据框连续绘制直方图
- maven - Serenity BDD 报告项目名称作为变量
- ssas - 与 2014 年相比,2017 年和 2016 年 SSAS 表格中的性能问题
- gradle - JetifyTransform Flutter 运行执行失败
- ruby-on-rails - 如何使用 Authentication Devise 调用 Sign_in 方法?
- powershell - Powershell exe到ico转换器损坏的图标