【问题标题】:How to use WebClient to execute synchronous request?如何使用 WebClient 执行同步请求?
【发布时间】:2020-03-04 03:54:50
【问题描述】:

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;

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

如何执行同步请求?

【问题讨论】:

标签: java spring spring-boot spring-webflux spring-webclient


【解决方案1】:

有效:

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

【讨论】:

  • 同步请求意味着阻塞,所以你已经提到,你添加 juste block()
  • @gstackoverflow 在调用 block() 方法后,你是如何得到你的 resp 值的?
  • @AM .block() 返回响应
  • 如何进行同步调用并获取响应码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 2011-10-04
  • 2021-04-27
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
相关资源
最近更新 更多