代码之家  ›  专栏  ›  技术社区  ›  Simon Sudhin

Spring RestTemplate-成批传递GET请求

  •  0
  • Simon Sudhin  · 技术社区  · 9 年前

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

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

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

    我查看了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只是扩展了SimpleClientHttpRequest工厂,以便我可以成功地获得重定向链接: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/AsyncRestTemplate.html#AsyncRestTemplate--

    1 回复  |  直到 9 年前
        1
  •  2
  •   Brian Clozel    9 年前

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

    你可以使用 the asynchronous variant of RestTemplate 并并行进行这些呼叫。