java - 使用 AsyncRestTemplate 多次制作 API 并等待所有完成

标签 java spring multithreading future asyncresttemplate

我必须使用不同参数多次使用 RestTemplate 进行 Rest API 调用。 API 相同,但它是正在更改的参数。次数也是可变的。我想使用 AsyncRestTemplate 但我的主线程应该等到所有 API 调用都已成功完成。我还想处理每个 API 调用返回的响应。目前我正在使用 RestTemplate。基本形式如下。

List<String> listOfResponses = new ArrayList<String>();
for (Integer studentId : studentIdsList) {
    String respBody;
    try {
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, requestEntity, String.class);
    } catch (Exception ex) {
        throw new ApplicationException("Exception while making Rest call.", ex);
    }
    respBody = requestEntity.getBody();
    listOfResponses.add(respBody);          
}

在这种情况下如何实现 AsyncRestTemplate?

最佳答案

使用 AsyncRestTemplate(或任何异步 API,事实上)的主要思想是在第一次发送所有请求,保留相应的 futures,然后在第二次处理所有响应.您可以简单地使用 2 个循环执行此操作:

List<ListenableFuture<ResponseEntity<String>>> responseFutures = new ArrayList<>();
for (Integer studentId : studentIdsList) {
    // FIXME studentId is not used
    ListenableFuture<ResponseEntity<String>> responseEntityFuture = restTemplate.exchange(url, method, requestEntity, String.class);
    responseFutures.add(responseEntityFuture);
}
// now all requests were send, so we can process the responses
List<String> listOfResponses = new ArrayList<>();
for (ListenableFuture<ResponseEntity<String>> future: responseFutures) {
    try {
        String respBody = future.get().getBody();
        listOfResponses.add(respBody);
    } catch (Exception ex) {
        throw new ApplicationException("Exception while making Rest call.", ex);
    }
}

注意:如果您需要将响应与原始请求配对,您可以将 future 列表替换为映射或请求+响应对象列表。

我还注意到您的问题中未使用 studentId

关于java - 使用 AsyncRestTemplate 多次制作 API 并等待所有完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425641/

相关文章:

java - 从 JSON 负载中获取特定属性作为 MVC 方法参数

java - 使用SSO时如何处理Http session 超时

java - 使用 RestTemplate 设置安全 cookie

java - 继续程序执行

java - 将本地日期/时间转换为 UTC 日期/时间 java SE 8

java - 如何从 persistence.xml 引用外部 hibernate.cfg.xml

c++ - decltype 和模板的问题

python - 给出 AttributeError 的多处理示例

c++ - 可以在调用构造函数之前完成赋值吗?

java - Spring/Java 从一个方法调用变量作为变量