如何等待所有请求完成

Raj*_*ajV 5 ning asynchttpclient

我正在AsyncHttpClient从命令行程序使用 ning。我需要等待所有请求结束,以便我可以安全地调用close()客户端。挑战在于我从该计划的许多不同部分提出了许多请求。onCompleted下面剥离了自己的代码,显示了我从另一个请求执行嵌套 HTTP 请求的场景:

final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

Future<Response> f1 = asyncHttpClient.prepareGet(url).execute(
    new AsyncCompletionHandler<Response>() {

        public Response onCompleted(Response response)
            throws Exception {

            //Make more HTTP calls
            Future f2 = asyncHttpClient.prepareGet(url).execute(...);

            return response;
        }
    });
Run Code Online (Sandbox Code Playgroud)

这只是示例代码。真实的代码更加复杂并且有更多的 HTTP 调用。close()在我呼叫客户之前确保所有呼叫都已完成的最佳方法是什么?

Tim*_*aer 1

对于较少数量的请求,收集所有Futures 然后使用CompletableFuture.allOf(futureCollection).get()可能会起作用。

根据文档,这也可以工作(尚未测试)

((DefaultAsyncHttpClient)asyncHttpClient)
  .getEventLoopGroup()
  .awaitTermination(1, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)