Simon
Simon

Reputation: 19938

Spring RestTemplate - passing in batches of GET requests

I need to query a server for links that can be obtained by giving the server a reference.

Lets say I have 10 references and I want to get 10 links back all in one go in an arrayList.

Is the below the most efficient way to do it? It looks pretty resource intensive and takes approximately 4672ms to generate

I looked at the docs for 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- but there doesn't seem to be an easier way to do what I want to do.

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

EDIT:

Based on suggestions, I have changed my code to but I'm getting an error: "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());
}

I looked at the reference docs but none of the constructors allow for me to set both a AsyncListenableTaskExecutor and a ClientHttpRequestFactory (the ClientHttpRequestFactory I used - CustomClientHttpRequestFactory just extends SimpleClientHttpRequestFactory so that I can get redirect links successfully: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/AsyncRestTemplate.html#AsyncRestTemplate--

Upvotes: 0

Views: 5972

Answers (1)

Brian Clozel
Brian Clozel

Reputation: 59086

Here you're making those REST calls sequentially - i.e. nothing is done in parallel.

You could use the asynchronous variant of RestTemplate and make those calls in parallel.

Upvotes: 2

Related Questions