How to write asynchronous REST client?
My controller (not sure if it's enough for being async):
@RequestMapping(method = RequestMethod.GET, value = "/get/all")
@ResponseBody
public Callable < CustomersListDTO > getAllCustomers() {
return new Callable < CustomersListDTO > () {
@Override
public CustomersListDTO call() throws Exception {
Thread.sleep(2000);
return customerService.getAllCustomers();
}
};
}
My synchronous REST client method:
public Response get_all_customers() {
ResponseEntity < CustomersListDTO > response;
try {
response = restTemplate.getForEntity(
getMethodURI(ServiceExplanation.GET_ALL_CUSTOMERS),
CustomersListDTO.class
);
message = "Customers obtained successfully!";
} catch (HttpServerErrorException ex) {
message = "ERROR: " + ex.getMessage() + " - " + ex.getResponseBodyAsString();
} catch (HttpClientErrorException ex) {
message = "ERROR: " + ex.getMessage() + " - " + ex.getResponseBodyAsString();
} catch (RestClientException ex) {
message = checkIfServerOrInternetDown();
}
return formResponse(message, response);
}
How do I make it asynchronous? How can the CLIENT continue doing other tasks while SERVER is obtaining data and later return found data?
Synchronous API calls are blocking calls that do not return until either the change has been completed or there has been an error. For asynchronous calls, the response to the API call is returned immediately with a polling URL while the request continues to be processed.
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.
The differences between asynchronous and synchronous include: Async is multi-thread, which means operations or programs can run in parallel. Sync is single-thread, so only one operation or program will run at a time.
If you are looking for REST asynchronous client implementation, you can take a look at Jersey's asynchronous client API. It can be easily integrated with Spring.
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