Spring RestTemplate - 批量传递 GET 请求

Spring RestTemplate - passing in batches of GET requests

我需要向服务器查询链接,可以通过给服务器一个引用来获得链接。

假设我有 10 个引用,我想在 arrayList 中一次获得 10 个链接。

下面是最有效的方法吗?它看起来非常耗费资源,生成大约需要 4672 毫秒

我查看了 RestTemplate 的文档:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#getForEntity-java.lang.String-java.lang.Class-java.util.Map- 但似乎没有更简单的方法来完成我想做的事情。

ArrayList<String> references = new ArrayList<>();
ArrayList<String> links = new ArrayList<>();
RestTemplate restTemplate = new RestTemplate(); 
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
for (int i = 0; i < 10; i++) {
    ResponseEntity<String> resource = restTemplate.getForEntity(references.get(i), String.class);
    links.add(resource.getBody().toString());
}

编辑:

根据建议,我已将代码更改为:"Asynchronous execution requires an AsyncTaskExecutor to be set":

ArrayList<String> references = new ArrayList<>();
ArrayList<String> links = new ArrayList<>();
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(new CustomClientHttpRequestFactory()); 
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
for (int i = 0; i < 10; i++) {
    Future<ResponseEntity<String>> resource = asyncRestTemplate.getForEntity(references.get(i), String.class);
    ResponseEntity<String> entity = resource.get(); //this should start up 10 threads to get the links asynchronously
    links.add(entity.getBody().toString());
}

我查看了参考文档,但 none 构造函数允许我同时设置 AsyncListenableTaskExecutor 和 ClientHttpRequestFactory(我使用的 ClientHttpRequestFactory - CustomClientHttpRequestFactory 只是扩展了 SimpleClientHttpRequestFactory 以便我可以成功获得重定向链接: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/AsyncRestTemplate.html#AsyncRestTemplate--

在这里,您将按顺序进行这些 REST 调用 - 即没有并行执行任何操作。

您可以使用 the asynchronous variant of RestTemplate 并并行进行这些调用。