【问题标题】:Spring RestTemplate - passing in batches of GET requestsSpring RestTemplate - 传入批量 GET 请求
【发布时间】:2015-07-21 19:46:33
【问题描述】:

我需要向服务器查询可以通过给服务器提供参考获得的链接。

假设我有 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());
}

编辑:

根据建议,我已将代码更改为,但出现错误:“异步执行需要设置 AsyncTaskExecutor”:

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

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

【问题讨论】:

  • 您可以使用Iterator 代替references.get(i)。您无需在响应正文上调用.toString(),它已经是String。考虑在 codereview 上提出这个问题。
  • 您不需要每次都添加StringHttpMessageConverter。一次就足够了,但请注意,默认情况下应该已经注册了一个。
  • 您也不需要在每次循环迭代时创建一个新的RestTemplate。一次就够了。
  • 谢谢 - 但我仍然调用服务器 10 次以取回 10 个链接。有什么更高效的办法吗?
  • 除非您的服务器支持批处理 API,否则不会。

标签: java spring resttemplate


【解决方案1】:

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

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

【讨论】:

  • 谢谢 - 我认为您的回答是最好的,因此我将其标记为正确。但是我确实注意到,如果我使用 resttemplate 的异步版本,rest 请求需要更长的时间才能返回,而不是同步版本,这很奇怪……我很快就会在上面发布一个新问题。
  • 链接失效
猜你喜欢
  • 2017-09-14
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 2013-10-02
  • 1970-01-01
相关资源
最近更新 更多