簡體   English   中英

如何在循環中調用rest API

[英]How to call rest API in the loop

我想使用 RestTemplate 多次調用第三方 API(對於每個客戶 ID,我必須調用 REST API)目前我已經編寫如下並且它工作正常但是它需要時間因為有很多客戶我會調用 API對於每個客戶 ID,有什么方法可以使它並行。

 public List<Organization> getCustomeOrganizationInfo(){
   String url="https://url.net/core/v1/customers"
   List<Organization> organizationList = new ArrayList<>();

    for(Customer customer:CustomerList){

      String restUrlWithUserId=url+"/customer.getCustomerId"

        CustomerInfo customerInfo = restTemplate.exchange(
                restUrlWithUserId,
                HttpMethod.GET,
                request,
                String.class
        );
        
    Organization organization =new Organization();
    organization.setCustomerId(customer.getCustomerId())
    organization.setorganizationId(customerInfo.getCustomeOrganizationId())
    organization.setorganizationname(customerInfo.getCustomeOrganizationName())
        
   organizationList.add(organization)       
}

}

有什么辦法可以讓這個並行

為了並發和干凈的代碼,您應該將 restTemplate 調用分離到另一個類(服務),例如ThirdPartyCustomerService.java 這個class會負責對外打電話。

@Service
public class ThirdPartyCustomerService {
   private final RestTemplate restTemplate;
   private final String url = '...';
   ...
   public CustomerInfo getCustomerInfo() {
       return this.restTemplate...
   }
}

然后你可以將這個 class 注入到你的服務 class 中。現在如果你想並發運行它。 您可以在此處嘗試@AsyncFuture 只需要對新服務進行一些更改,並記住在您的主要服務上調用 Future.get() 。

@Async
public Future<CustomerInfo> getCustomerInfo() {
   return new AsyncResult<CustomerInfo>(this.restTemplate...);
}

或者您可以使用 WebClient,它是 RestTemplate 和 AsyncRestTemplate 的替代方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM