使用Akka HTTP调用多个API

时间:2018-11-10 15:03:00

标签: java akka-http

我是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).;

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

1 个答案:

答案 0 :(得分:0)

我对java的{​​{1}}版本不太熟悉,因此下面的示例代码可能无法编译,但演示了一般的想法...

大概您具有将先前API调用的响应转换为对下一个API的请求的功能:

akka

然后可以将这些转换器放在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));