1
"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.

Draken
  • 3,134
  • 13
  • 34
  • 54
huk12353
  • 23
  • 4
  • And do you have a question? – stdunbar Nov 01 '21 at 19:18
  • The question is how can I call the rest endpoint with the concurrent request,? I know how to call single-threaded using rest templates. – huk12353 Nov 01 '21 at 19:24
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! See also: [ask] – Draken Nov 02 '21 at 07:31

1 Answers1

4

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);
gkatiforis
  • 1,588
  • 9
  • 19