![](/img/trans.png)
[英]Concurrent asynchronous HTTP requests in Java and/or Spring Boot
[英]waiting on asynchronous http requests in java
我正在使用Jetty HTTP Client異步進行約50個HTTP調用。 代碼看起來像這樣:
List<Address> addresses = getAddresses();
final List<String> done = Collections.synchronizedList(new LinkedList<String>());
List<ContentExchange> requests;
for (Address address : addresses) {
ContentExchange ce = new ContentExchange() {
@Override
protected void onResponseComplete() throws IOException {
//handle response
done.add("done");
}
}
ce.setURL(createURL(address));
requests.add(ce);
}
for (ContentExchange ce : requests) {
httpClient.send(ce);
}
while (done.size() != addresses.size()) {
Thread.yield();
}
System.out.println("All addresses processed");
它正在調用Rest服務,該服務返回有關該地址的一些數據。 我期望它是這樣的:
但是,它不起作用。 如果沒有while循環,它會很好地工作,但是我需要等到所有50個都完成之后。 有沒有辦法等到全部50個完成?
我也了解ExecutorService和多線程解決方案,但是我需要具有無阻塞IO的單線程解決方案。
使用java.util.concurrent.CountDownLatch
進行管理。
Eclipse Jetty 8.1.10.v20130312的Siege.java測試類的示例 :
final CountDownLatch latch = new CountDownLatch(concurrent);
for (int i=0;i<concurrent;i++)
{
ConcurrentExchange ex = new ConcurrentExchange(client,latch,uris,repeats);
if (!ex.next()) // this executes the client.send()
{
latch.countDown(); // count down if client.send() was in error
}
}
latch.await(); // wait for all ConcurrentExchange's to complete (or error out)
注意: ConcurrentExchange是Siege.java中的私有類。
然后在您的HttpExchange
對象中,在以下方法中使用CountDownLatch.countDown()
調用
請注意,所有示例都使用AtomicBoolean counted
,以確保僅計數一次。
if (!counted.getAndSet(true)) // get the value, then set it to true
{
// only get here if counted returned false. (and that will only happen once)
latch.countDown(); // count down this exchange as being done.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.