2014-01-10 69 views
6

如何編寫異步休息客戶端?我的控制器(不知道它是不是異步)。異步REST客戶端

@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(); 
      } 
     }; 
    } 

我同步其餘客戶方法:

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); 
    } 

如何使它異步?在SERVER獲取數據並在以後返回找到的數據時,CLIENT如何繼續執行其他任務?

+0

閱讀有關併發性。 http://docs.oracle.com/javase/tutorial/essential/concurrency/ – gouki

+0

請看以下鏈接https://www.adayinthelifeof.nl/2011/06/02/asynchronous-operations-in-rest/ – sasankad

回答

0

我會建議在您的應用程序中添加對groovy的支持,以便您可以使用AsyncHTTPBuilder,這是您正在嘗試執行的操作。它基本上使用FutureTask的封面。

5

如果你正在尋找REST異步客戶端實現,你可以看看Jersey的asynchronous client API。它可以很容易地與Spring集成。

+0

謝謝您!得到它的工作。 – user1335163