简体   繁体   English

如何使用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. Spring 文档指出,即使我们要执行同步 http 调用,我们也必须从 RestTemplate 切换到WebClient

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.当然我可以在这里使用 CountdownLatch,但它看起来像 API 误用。

How could I execute synchronous request?我怎么能执行同步请求?

It works:有用:

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

!!!Attention!!! !!!注意力!!!

For a fresh version of webflux please use:对于新版本的 webflux,请使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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