如何等待所有请求完成 [英] How to wait for all requests to finish

查看:294
本文介绍了如何等待所有请求完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在命令行程序中使用 AsyncHttpClient 。我需要等待所有请求结束,以便可以安全地在客户端上调用 close()。挑战在于,我从程序的许多不同部分发出了许多请求。下面的剥离的自己的代码显示了一种情况,其中我从另一个请求的 onCompleted 进行了嵌套HTTP请求:

I am using ning AsyncHttpClient from a command line program. I need to wait for all requests to end so I can safely call close() on the client. The challenge is that I make many requests from many different parts of the program. Stripped own code below that shows one scenario where I do a nested HTTP request from the onCompleted of another request:

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;
        }
    });

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

This is an example code only. Real code is more complex and has many more HTTP calls. What will be the best way to make sure all calls are finished before I call close() for the client?

推荐答案

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

For smaller number of requests, collecting all Futures and then use CompletableFuture.allOf(futureCollection).get() might work.

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

According to the docs, this could work as well (not tested yet)

((DefaultAsyncHttpClient)asyncHttpClient)
  .getEventLoopGroup()
  .awaitTermination(1, TimeUnit.MINUTES);

这篇关于如何等待所有请求完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆