I want to call the third party API multiple times using the RestTemplate(for each customer id I have to call REST API) currently I have written like below and its working fine but it's taking time because there are many customers I'd and calling API for each customer id, is there any way I can make this parallel.
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)
}
}
For concurrency and clean code, you should separate your restTemplate call to another class(service), for example,
ThirdPartyCustomerService.java. This class will be held responsible for calling outside.Then you can inject this class into your service class. Now if you want to run it concurrency. You could try
@AsyncandFuturehere. Just need a little bit of change on the new service and remember to call Future.get() on your main service.Or you can use WebClient, an alternative for RestTemplate and AsyncRestTemplate.