使用 AsyncRestTemplate 多次制作 API 并等待所有完成 [英] Make API multiple times with AsyncRestTemplate and wait for all to complete

查看:87
本文介绍了使用 AsyncRestTemplate 多次制作 API 并等待所有完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to make Rest API invocation using RestTemplate multiple time with different parameters. API is same but it is the parameter that is getting changed. Number of times is also variable. I want to use AsyncRestTemplate but my main Thread should wait until all API calls have been successfully completed. I also want to work with responses that each API call returned. Currently I am using RestTemplate. In basic form it is as following.

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?

How can I implement AsyncRestTemplate in this situation?

推荐答案

使用 AsyncRestTemplate(或任何异步 API,事实上)的主要思想是在第一时间发送所有请求,保留相应的期货,然后第二次处理所有响应.你可以简单地用 2 个循环来做到这一点:

The main idea when using AsyncRestTemplate (or any asynchronous API, in fact), is to send all you requests in a first time, keeping the corresponding futures, then process all responses in a second time. You can simply do this with 2 loops:

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);
    }
}

注意:如果您需要将响应与原始请求配对,您可以将期货列表替换为地图或请求+响应对象列表.

Note: if you need to pair the responses with the original requests, you can replace the list of futures with a map or a list of request+response objects.

我还注意到您的问题中没有使用 studentId.

I also noted that studentId is not used in your question.

这篇关于使用 AsyncRestTemplate 多次制作 API 并等待所有完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆