Reputation: 91
I have a rest endpoint exposed to get data from multiple systems using rest web services. all are independent calls queried using the single primary key with Spring resttemplate.
I used CompletableFuture to call each API first then at end waiting for their response. here in log I do see the calls happened up to the resttemplate exchange methods are happening in parallel but once after that each threads are going in sequential or waiting for another thread to complete.
`CompletableFuture<TypeA> callA = CompletableFuture
.supplyAsync(() -> getCallA(id),
traceableExecutorService);
CompletableFuture<TypeB> callB = CompletableFuture
.supplyAsync(() -> getCallB(id),
traceableExecutorService);
CompletableFuture<TypeC> callC = CompletableFuture
.supplyAsync(() -> getCallC(id),
traceableExecutorService);
try {
TypeA = callA.get();
TypeB = callB.get();
TypeC = callC.get();
} catch (InterruptedException | ExecutionException e) {
throw e;
}
// code create response and return...
`
rest template config
` @Bean public RestTemplate restTemplate() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setRetryHandler(
new DefaultHttpRequestRetryHandler(3, true));
httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(10000)
.setSocketTimeout(10000).build());
httpClientBuilder.setMaxConnTotal(2000);
httpClientBuilder.setMaxConnPerRoute(100);
HttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
httpClient);
clientHttpRequestFactory.setConnectTimeout(10000);
clientHttpRequestFactory.setReadTimeout(10000);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(clientHttpRequestFactory);
restTemplate.setInterceptors(Collections.singletonList(new RequestResponseLoggingInterceptor()));
return restTemplate;
}
` thread pool
new TraceableExecutorService(factory, Executors.newWorkStealingPool(20000))
Upvotes: 0
Views: 396
Reputation: 1
You have to join all 3 tasks. So it will be started in parallel and next step will be processed only when all 3 tasks are completed.
CompletableFuture.allOf(callA , callB, callC).join();
Upvotes: 0