gpt4 book ai didi

spring-boot - Spring WebClient 作为 RestTemplate 的替代品

转载 作者:行者123 更新时间:2023-12-05 00:46:55 37 4
gpt4 key购买 nike

RestTemplate 的当前 javadoc 状态:

NOTE: As of 5.0, the non-blocking, reactive org.springframework.web.reactive.client.WebClient offers a modern alternative to the RestTemplate with efficient support for both sync and async, as well as streaming scenarios. The RestTemplate will be deprecated in a future version and will not have major new features added going forward.



我们正在使用 spring boot 2.0.6 和 spring 5.0.10 编写一个新项目。

看到 restTemplate 将被弃用,我们决定使用新的 WebClient,它也应该支持同步调用。但我找不到任何关于如何实现这一目标的文档。

我在下面的代码中使用了 block :
ResponseEntity<String> response = webClient.get()
.uri(url)
.exchange()
.flatMap(r -> r.toEntity(String.class))
.block();

但是,当从 Spring Controller 调用时,这会引发以下异常
java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread

那么究竟应该如何以同步方式使用 WebClient 呢?

编辑:我的 pom.xml 看起来像这样:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

最佳答案

如果您的应用程序只是使用 spring-boot-starter-webflux ,这意味着服务器和客户端都将使用 Spring WebFlux。在这种情况下,禁止调用block Controller 处理程序中的运算符,因为它会阻塞少数服务器线程之一,并会产生重要的运行时问题。

如果这背后的主要驱动是使用WebClient ,那么您可以同时依赖 spring-boot-starter-webspring-boot-starter-webflux .您的 Spring Boot 应用程序仍将在服务器端使用 Spring MVC,您将能够使用 WebClient作为客户。
在这种情况下,您可以调用 block运营商甚至使用 FluxMono作为 Controller 中的返回类型,as Spring MVC supports that .你甚至可以gradually introduce WebClient in an existing Spring MVC application .

关于spring-boot - Spring WebClient 作为 RestTemplate 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083790/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com