javaspringspring-bootspring-webfluxspring-webclient

How to use WebClient to execute synchronous request?


Spring documentation states that we have to switch from RestTemplate to WebClient even if we want to execute Synchronous HTTP call.

For now I have following code:

  Mono<ResponseEntity<PdResponseDto>> responseEntityMono = webClient.post()
                .bodyValue(myDto)
                .retrieve()
                .toEntity(MyDto.class);
        responseEntityMono.subscribe(resp -> log.info("Response is {}", resp));
   //I have to return response here
   // return resp;

Sure I could use CountdownLatch here but it looks like API misusing.

How could I execute synchronous request ?


Solution

  • UPDATE

    In a new library version please use:

    webClient.post()
             .bodyValue(myDto)
             .retrieve()
             .toEntity(MyDto.class)
             .toFuture()
             .get();
    

    Old answer (for old version of library)

    It works:

    webClient.post()
             .bodyValue(myDto)
             .retrieve()
             .toEntity(MyDto.class)
             .block(); // <-- This line makes trick