Spring WebClient作为RestTemplate的替代方案

9
目前RestTemplate的javadoc声明:
注意:自5.0版本以来,非阻塞式反应org.springframework.web.reactive.client.WebClient提供了一种现代替代RestTemplate的方法,支持同步和异步以及流式场景的高效支持。 RestTemplate将在未来的一个版本中被弃用,并且不会添加重大新功能。
我们正在使用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>
1个回答

12
如果你的应用只使用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

3
缺少的 spring-boot-starter-web 是罪魁祸首。现在可以工作了。谢谢! - Ramona Cristea
我们是否需要添加 spring-boot-starter-web 才能使用同步的 WebClient?似乎我可以在不添加它的情况下使用同步的 WebClient - mazend
哦...我们仍然需要spring-boot-starter-web来使用同步的WebClient。而且似乎spring-cloud-starter-netflix-eureka-server包含了spring-boot-starter-web,所以我误解了。 - mazend

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接