2017-11-30 9 views
0

私の要件は、私はRESTアプリケーションで複数のAPIを呼び出す必要があります。私は、それぞれのAPIが別のAPIからの応答を待っているかどうかにかかわらず、独立して動作するようにしたい。つまり私は、以下のようにあなたが別のスレッド内API電話をかけることができますつのAPIリクエストが5秒を取るならば、すべてのAPIリクエストも同時に複数のApiリクエストをspring mvcで呼び出します

答えて

0

を5秒を取るべきである必要があります。

new Thread(new Runnable() { 
public void run() { 
try { 
// Do your api call here 
} 
catch(Exception e) 
{// Log or do watever you need} 
} 

このようにAPIコールがasynchronouslyに動作します!

0

org.springframework.web.client.AsyncRestTemplateクラスを使用すると、ListenableFutureを返して値を非同期的に取得できます。したがって、あなたのメソッドは最も遅いapi呼び出しと同じ時間がかかります。

public static void main(String[] args) { 
    AsyncRestTemplate asycTemp = new AsyncRestTemplate(); 
    HttpMethod method = HttpMethod.GET; 
    // create request entity using HttpHeaders 
    HttpHeaders headers = new HttpHeaders(); 
    headers.setContentType(MediaType.TEXT_PLAIN); 
    HttpEntity<String> requestEntity = new HttpEntity<String>("params", headers); 
    ListenableFuture<ResponseEntity<String>> future = asycTemp.exchange("https://www.google.com", method, requestEntity, String.class); 
    ListenableFuture<ResponseEntity<String>> future1 = asycTemp.exchange("https://www.yahoo.com", method, requestEntity, String.class); 
    ListenableFuture<ResponseEntity<String>> future2 = asycTemp.exchange("https://www.bing.com", method, requestEntity, String.class); 
    try { 
     // waits for the result 
     ResponseEntity<String> entity = future.get(); 
     // prints body source code for the given URL 
     System.out.println(entity.getBody()); 
     entity = future1.get(); 
     System.out.println(entity.getBody()); 
     entity = future2.get(); 
     System.out.println(entity.getBody()); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 
} 
関連する問題