Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous REST client

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?

like image 327
user1335163 Avatar asked Jan 10 '14 02:01

user1335163


People also ask

What is an asynchronous API call?

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.

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.

What is asynchronous vs synchronous?

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.


1 Answers

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.

like image 198
tonga Avatar answered Oct 02 '22 20:10

tonga