首页 > 解决方案 > 使用 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).;

对此的任何帮助将不胜感激。

标签: javaakka-http

解决方案


我不太熟悉的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).;

推荐阅读