改编自Waiting for callback for multiple futures。
此示例仅请求 Google 和 Microsoft 主页。当在回调中收到响应并且我完成了处理时,我减少了CountDownLatch。我等待 CountDownLatch,“阻塞”当前线程,直到 CountDownLatch 达到 0。
如果您的调用失败或成功,请务必减少,因为您必须点击 0 才能继续该方法!
public static void main(String[] args) throws Exception {
String googleUrl = "http://www.google.com";
String microsoftUrl = "http://www.microsoft.com";
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
ListenableFuture<ResponseEntity<String>> googleFuture = asyncRestTemplate.exchange(googleUrl, HttpMethod.GET, null, String.class);
ListenableFuture<ResponseEntity<String>> microsoftFuture = asyncRestTemplate.exchange(microsoftUrl, HttpMethod.GET, null, String.class);
final CountDownLatch countDownLatch = new CountDownLatch(2);
ListenableFutureCallback<ResponseEntity<java.lang.String>> listenableFutureCallback = new ListenableFutureCallback<ResponseEntity<String>>() {
public void onSuccess(ResponseEntity<String> stringResponseEntity) {
System.out.println(String.format("[Thread %d] Status Code: %d. Body size: %d",
Thread.currentThread().getId(),
stringResponseEntity.getStatusCode().value(),
stringResponseEntity.getBody().length()
));
countDownLatch.countDown();
}
public void onFailure(Throwable throwable) {
System.err.println(throwable.getMessage());
countDownLatch.countDown();
}
};
googleFuture.addCallback(listenableFutureCallback);
microsoftFuture.addCallback(listenableFutureCallback);
System.out.println(String.format("[Thread %d] This line executed immediately.", Thread.currentThread().getId()));
countDownLatch.await();
System.out.println(String.format("[Thread %d] All responses received.", Thread.currentThread().getId()));
}
我的控制台的输出:
[Thread 1] This line executed immediately.
[Thread 14] Status Code: 200. Body size: 112654
[Thread 13] Status Code: 200. Body size: 19087
[Thread 1] All responses received.