spring async rest client编排好几个电话

时间:2016-02-05 19:33:41

标签: java spring spring-web

我在服务中遇到以下问题我正在构建对象X但是为了构建它我需要进行几次http调用以获取所有必需的数据来填充它(每个休息填充对象的某些部分。)在为了保持高性能,我认为调用异步并在完成所有调用之后将对象返回给调用者会很好。它看起来像这样

ListenableFuture<ResponseEntity<String>> future1 = asycTemp.exchange(url, method, requestEntity, responseType);
future1.addCallback({
    //process response and set fields
    complexObject.field1 = "PARSERD RESPONSE"
},{
    //in case of fail fill default or take some ather actions
})

我不知道如何等待所有功能完成。我猜他们是解决这类问题的标准弹簧方式。在此先感谢您的任何建议。 Spring版本 - 4.2.4.RELEASE 最好的问候

1 个答案:

答案 0 :(得分:2)

改编自Waiting for callback for multiple futures

此示例只是请求Google和Microsoft主页。当回调中收到回复,并且我已完成处理时,我减少CountDownLatch。我在等待CountDownLatch,&#34;阻止&#34;当前线程直到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.