Issue
"url":"https://asia-east2-jsondoc.cloudfunctions.net/function-1?delay=1000" //url that takes 1000 ms to return "isParallel": true, "count": "3"
isParallel = true means make parallel calls, false means – make a sequential call, count represents the number of parallel or sequential calls to make.
I have to call the above endpoint and the output should be 1 sec.
How can I call the rest endpoint with the concurrent request? I know how to call single-threaded using rest templates.
Solution
Use RestTemplate
with ExecutorService
Using ExecutorService
to perform 3 concurrent calls with RestTemplate
:
Strnig url = "https://asia-east2-jsondoc.cloudfunctions.net/function-1?delay=1000";
RestTemplate restTemplate = new RestTemplate();
ExecutorService executor = Executors.newFixedThreadPool(3);
Future<String> future1 = executor.submit(() -> restTemplate.getForObject(url , String.class));
Future<String> future2 = executor.submit(() -> restTemplate.getForObject(url , String.class));
Future<String> future3 = executor.submit(() -> restTemplate.getForObject(url , String.class));
String response1 = future1.get();
String response2 = future2.get();
String response3 = future3.get();
executor.shutdown();
Use reactive WebClient
Using reactive WebClient
to perform 3 concurrent calls and display the response in subscribe
callback:
String url = "https://asia-east2-jsondoc.cloudfunctions.net/function-1?delay=5000";
WebClient webClient = WebClient.builder().build();
Mono<String> mono1 = webClient.get().uri(url).retrieve().bodyToMono(String.class);
Mono<String> mono2 = webClient.get().uri(url).retrieve().bodyToMono(String.class);
Mono<String> mono3 = webClient.get().uri(url).retrieve().bodyToMono(String.class);
Flux.merge(mono1, mono2, mono3).subscribe(System.out::println);
Answered By - gkatiforis