简体   繁体   中英

Call Rest end point with concurrent request

"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 above endpoint and output should be 1 sec.

The question is how can I call the rest endpoint with the concurrent request? I know how to call single-threaded using rest templates.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM