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);
}
How can I implement AsyncRestTemplate in this situation?
We can write asynchronous code with Python by using a library called Asyncio, though. Python has another library called Aiohttp that is an HTTP client and server based on Asyncio. Thus, we can use Asyncio to create asynchronous API calls. This is useful for optimizing code.
When processing a request asynchronously we should provide a way for the client to get the current processing status. This can be done by introducing a separate status resource. The client can then request this resource in regular intervals until the operation has been completed.
REST services has not nothing to do with being Synchronous or asynchronous. Client Side: Clients calling must support asynchronous to achieve it like AJAX in browser. Server Side: Multi- Thread environment / Non blocking IO are used to achieve asynchronous service.
AsyncRestTemplate allows users to make asynchronous service calls. The logic is similar to restTemplate, except that the service is called asynchronously.
You could use Java 8 Stream API, if that's feasible for you:
List<String> listOfResponses = studentIdsList.stream()
.parrallel()
.map({studentId ->
ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, studentId, String.class);
return responseEntity.getBody();
})
.collect(Collectors.toList());
This code will basically perform 2 things:
UPDATE: Agree with @Didier L - this solution may not work properly when you need to do a lot of requests. Here is an updated version:
List<String> listOfResponses = studentIdsList.stream()
.map(studentId -> asyncRestTemplate.exchange(url, method, studentId, String.class)
.collect(Collectors.toList()).stream()
.map(this::retrieveResult)
.collect(Collectors.toList());
/**
* Retrieves results of each request by blocking the main thread. Note that the actual request was performed on the previous step when
* calling asyncRestTemplate.exchange(url, method, studentId, String.class)
*/
private String retrieveResult(ListenableFuture<ResponseEntity<String>> listenableFuture) {
try {
return listenableFuture.get().getBody();
} catch (Exception e) {
e.printStackTrace();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With