如何使用Apache Beam(Java)进行异步Http调用?

时间:2018-04-17 18:20:16

标签: apache-beam asynchttpclient

输入PCollection是http请求,这是一个有界数据集。我想在ParDo中进行异步http调用(Java),解析响应并将结果放入输出PCollection中。我的代码如下。获得以下异常。

我不知道原因。需要一个指南......

java.util.concurrent.CompletionException: java.lang.IllegalStateException: Can't add element ValueInGlobalWindow{value=streaming.mapserver.backfill.EnrichedPoint@2c59e, pane=PaneInfo.NO_FIRING} to committed bundle in PCollection Call Map Server With Rate Throttle/ParMultiDo(ProcessRequests).output [PCollection]

代码

public class ProcessRequestsFn extends DoFn<PreparedRequest,EnrichedPoint> {
    private static AsyncHttpClient _HttpClientAsync;
    private static ExecutorService _ExecutorService;

static{

    AsyncHttpClientConfig cg = config()
            .setKeepAlive(true)
            .setDisableHttpsEndpointIdentificationAlgorithm(true)
            .setUseInsecureTrustManager(true)
            .addRequestFilter(new RateLimitedThrottleRequestFilter(100,1000))
            .build();

    _HttpClientAsync = asyncHttpClient(cg);

    _ExecutorService = Executors.newCachedThreadPool();

}


@DoFn.ProcessElement
public void processElement(ProcessContext c) {

    PreparedRequest request = c.element();

    if(request == null)
        return;

    _HttpClientAsync.prepareGet((request.getRequest()))
            .execute()
            .toCompletableFuture()
            .thenApply(response -> { if(response.getStatusCode() == HttpStatusCodes.STATUS_CODE_OK){
                                                return response.getResponseBody();
                                            } return null; } )
            .thenApply(responseBody->
                    {
                        List<EnrichedPoint> resList = new ArrayList<>();
                        /*some process logic here*/
                        System.out.printf("%d enriched points back\n", result.length());
                        }
                        return resList;

                    })
            .thenAccept(resList -> {
                for (EnrichedPoint enrichedPoint : resList) {
                    c.output(enrichedPoint);
                }
            })
            .exceptionally(ex->{
                System.out.println(ex);
                return null;
            });

  }
}

2 个答案:

答案 0 :(得分:2)

Scio库实现了处理异步操作的DoFnBaseAsyncDoFn可能会为您提供所需的处理。由于您正在处理CompletableFuture,因此请同时查看JavaAsyncDoFn

请注意,您不一定需要使用Scio库,但是您可以采用BaseAsyncDoFn的主要思想,因为它独立于Scio库的其余部分。

答案 1 :(得分:0)

您遇到的问题是您的输出超出了processElementfinishBundle调用的上下文。

您将希望将所有输​​出收集到内存中,并在以后的processElement通话期间和finishBundle的最后,通过阻塞直到所有通话结束,来急切地输出它们。