SpringBoot WebFlux - Making parallel WebClient requests

I'm trying to make parallel (batch) calls to the same rest service using the new SpringBoot 2 Reactive WebClient class(it does not have a batch endpoint). For example I need 100 "Comment" object (with ids 1...100) and I'm doing the following parallel calls :

    List<Mono<Comment>> monos = ids.stream()
            .map(id -> webClient.get()
                    .uri("/comments/{id}", id)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .bodyToMono(Comment.class))
            .collect(Collectors.toList());

    return Flux.merge(monos);

I'm new to Spring WebFlux and I'm not sure this is the right way of doing parallel calls with the WebClient

Regards

The full source code can be bound at : https://github.com/fdlessard/SpringBootReactiveComment

Upvotes: 4

Views: 7688

Answers (1)

Serg Vasylchak
Serg Vasylchak

Reputation: 874

Flux.fromIterable(ids)
  .flatMap(id -> webClient.get()
    .uri("/comments/{id}", id)
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .bodyToMono(Comment.class))
  .subscribeOn(Schedulers.parallel());

Upvotes: 2

Related Questions