java - spring 异步休息客户端编排一些调用

标签 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 方法。在此先感谢您的任何建议。 Spring 版本 - 4.2.4.RELEASE 最好的问候

最佳答案

改编自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.

关于java - spring 异步休息客户端编排一些调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232073/

相关文章:

java - 在java中无需打开浏览器即可检查url是否存在

java.sql.SQLException : HikariDataSource HikariDataSource (HikariPool-1) has been closed

java - Spring RestTemplate + 将 XML 结果映射到 Domain 对象

java - 在java中使用ftp下载时文件被损坏

java - 即使我没有告诉它,按钮也会触发frame.repaint()。我做错了什么?

java - 当我使用继承实体的存储库时如何修复 "No property [repositoryMethod] found for type [entity]!"?

java - Spring MVC 在 Dispatcher Servlet 中找不到映射

java - 如何使用@RequestBody 调用@RestController?

spring-boot - 在带有 Slice 的 Spring Boot 中使用 MockMVC 测试静态内容

java - 需要帮助保存和继续用户输入