Spring WebClient 作为 RestTemplate 的替代品

Ram*_*tea 6 resttemplate spring-boot project-reactor spring-webflux

RestTemplate 的当前 javadoc 状态:

注意:从 5.0 开始,非阻塞、反应式 org.springframework.web.reactive.client.WebClient 提供了 RestTemplate 的现代替代方案,有效支持同步和异步以及流场景。RestTemplate 将在未来版本中被弃用,并且不会在未来添加主要的新功能。

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

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

我为此使用了块,如下面的代码所示:

ResponseEntity<String> response = webClient.get()
            .uri(url)
            .exchange()
            .flatMap(r -> r.toEntity(String.class))
            .block();
Run Code Online (Sandbox Code Playgroud)

但是,当从弹簧控制器调用时,这会引发以下异常

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread
Run Code Online (Sandbox Code Playgroud)

那么究竟应该如何同步使用 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>
Run Code Online (Sandbox Code Playgroud)

Bri*_*zel 8

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

如果这背后的主要驱动程序是使用WebClient,那么您可以同时依赖spring-boot-starter-webspring-boot-starter-webflux。您的 Spring Boot 应用程序仍将在服务器端使用 Spring MVC,您将能够将其WebClient用作客户端。在这种情况下,您可以调用block运算符,甚至可以在控制器中使用FluxMono作为返回类型,因为 Spring MVC 支持。您甚至可以在现有的 Spring MVC 应用程序中逐步引入WebClient

  • 所以缺少的 `spring-boot-starter-web` 是罪魁祸首。现在工作。谢谢! (3认同)