如何使用 WebClient 执行同步请求?

gst*_*low 4 java spring spring-boot spring-webflux spring-webclient

Spring 文档说明我们必须从 RestTemplate 切换到WebClient即使我们想要执行同步 http 调用。

现在我有以下代码:

  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;
Run Code Online (Sandbox Code Playgroud)

当然我可以在这里使用 CountdownLatch 但它看起来像 API 滥用。

我怎么能执行同步请求?

gst*_*low 12

有用:

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

  • 同步请求意味着阻塞,因此正如您提到的,您添加 juste block() (2认同)
  • @AM .block() 返回响应 (2认同)