问题
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;
}
});
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?
回答1:
For smaller number of requests, collecting all Future
s 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);
来源:https://stackoverflow.com/questions/28548375/how-to-wait-for-all-requests-to-finish