dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Spring Simultaneous Reactive WebClient Requests #101

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

The Spring WebClient is a reactive webclient. In general the workflow with webclient is (in kotlin):

val webClient = WebClient.create("http://x.y.z.")
          .post()
          .uri("/events*/_search")
          .contentType(MediaType.APPLICATION_JSON)
          .accept(MediaType.APPLICATION_JSON)
          .body(BodyInserters.fromObject(someJSON))
          .exchange()
          .flatMap { clientResponse -> clientResponse.bodyToMono(String::class.java) }

In the above case, webClient will be a Mono<String>, which hasn't been executed yet (since there's no subscription). We can gather multiple such "webclients" into an array, and execute all simultaneously by using Flux.merge, for example:

val webClients = ArrayList<Mono<String>>()
webClients.add(webClient) // usually called multiple times

Flux.merge( webClients ).subscribe{ e -> println(e) } //web calls done simultaneously here