Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make API multiple times with AsyncRestTemplate and wait for all to complete

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?

like image 850
TV Nath Avatar asked Jun 08 '17 02:06

TV Nath


People also ask

How do you make an API asynchronous?

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.

How do you handle asynchronous calls in rest?

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.

Is rest asynchronous or synchronous?

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.

What is AsyncRestTemplate?

AsyncRestTemplate allows users to make asynchronous service calls. The logic is similar to restTemplate, except that the service is called asynchronously.


1 Answers

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:

  1. Performs requests in parallel;
  2. Collect the results of the requests into a List.

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();
        }
    }
like image 113
Danylo Zatorsky Avatar answered Oct 12 '22 15:10

Danylo Zatorsky