HTTP请求Java的Akka actor

时间:2018-11-12 14:20:12

标签: akka akka-http akka-actor

您好,我试图在AKKA中寻找一个简单的示例-Java创建一个Actor的HTTP客户端。到目前为止,我已经能够创建一个请求并获取响应Http Entity。我需要将其迁移到actor,以便可以在超时的情况下并行调用多个actor。

 final ActorSystem system = ActorSystem.create();
    final Materializer materializer = ActorMaterializer.create(system);

    final List<HttpRequest> httpRequests = Arrays.asList(
            HttpRequest.create(url) // Content-Encoding: gzip in respons

    );

    Unmarshaller<ByteString, BitTweet> unmarshal = Jackson.byteStringUnmarshaller(BitTweet.class);
    JsonEntityStreamingSupport support = EntityStreamingSupport.json();

    final Http http = Http.get(system);

    final Function<HttpResponse, HttpResponse> decodeResponse = response -> {
        // Pick the right coder
        final Coder coder;
        if (HttpEncodings.gzip().equals(response.encoding())) {
            coder = Coder.Gzip;
        } else if (HttpEncodings.deflate().equals(response.encoding())) {
            coder = Coder.Deflate;
        } else {
            coder = Coder.NoCoding;
        }

        // Decode the entity
        return coder.decodeMessage(response);
    };

    List<CompletableFuture<HttpResponse>> futureResponses = httpRequests.stream()
            .map(req -> http.singleRequest(req, materializer)
                    .thenApply(decodeResponse))
            .map(CompletionStage::toCompletableFuture)
            .collect(Collectors.toList());

    for (CompletableFuture<HttpResponse> futureResponse : futureResponses) {
        final HttpResponse httpResponse = futureResponse.get();

        system.log().info("response is: " + httpResponse.entity()
                .toStrict(1, materializer)
                .toCompletableFuture()
                .get());


        HttpEntity.Strict entity_ = HttpEntities.create(ContentTypes.APPLICATION_JSON, httpResponse.entity().toString());

                 Source<BitTweet, Object> BitTweet =
                         entity_.getDataBytes()
                        .via(support.framingDecoder()) // apply JSON framing
                        .mapAsync(1, // unmarshal each element
                                bs -> unmarshal.unmarshal(bs, materializer)


                        );

0 个答案:

没有答案