Asynchronous REST client

17,747

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.

Share:
17,747
user1335163
Author by

user1335163

Updated on June 04, 2022

Comments

  • user1335163
    user1335163 almost 2 years

    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?