Spring WebClient 作为 RestTemplate 的替代品

Spring WebClient as an alternative to RestTemplate

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 控制器

调用时,会抛出以下异常
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。在这种情况下,禁止在 Controller 处理程序中调用 block 运算符,因为它会阻塞少数服务器线程之一,并会产生重要的运行时问题。

如果这背后的主要驱动因素是使用 WebClient,那么您可以同时依赖 spring-boot-starter-webspring-boot-starter-webflux。您的 Spring 引导应用程序仍将在服务器端使用 Spring MVC,并且您将能够使用 WebClient 作为客户端。 在这种情况下,您可以调用 block 运算符,甚至可以在控制器中使用 FluxMono 作为 return 类型,as Spring MVC supports that. You can even gradually introduce WebClient in an existing Spring MVC application.