在spring mvc中同时调用多个Api请求

时间:2017-11-30 07:47:25

标签: spring rest spring-mvc

我的要求是,我必须在我的REST应用程序中调用多个API。我希望每个API都能独立工作,无论等待另一个API的响应。即如果一个API请求需要5秒,那么我需要所有api请求也需要5秒

2 个答案:

答案 0 :(得分:0)

您可以在单独的帖子中进行API调用,如下所示:

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

因此API调用将起作用asynchronously

答案 1 :(得分: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();
    }
}