天天看点

飞5的Spring Boot2(35)- 调用REST服务WebClient

调用REST服务 WebClient

如果你的类路径上有Spring WebFlux,你也可以选择使用WebClient来调用远程REST服务。相比之下RestTemplate,这个客户有更多的功能感,并且完全被动。您可以使用构建器创建您自己的客户端实例, WebClient.create()。请参阅WebClient上的相关部分。

飞5的Spring Boot2(35)- 调用REST服务WebClient

Spring Boot为您创建并预配置这样的构建器。例如,客户端HTTP编解码器的配置方式与服务器的相同(请参阅 WebFlux HTTP编解码器自动配置)。

以下代码显示了一个典型示例:

1@Service
 2public class MyService {
 3private final WebClient webClient;
 4public MyBean(WebClient.Builder webClientBuilder) {
 5this.webClient = webClientBuilder.baseUrl("http://example.org").build();
 6}
 7public Mono<Details> someRestCall(String name) {
 8return this.webClient.get().url("/{name}/details", name)
 9.retrieve().bodyToMono(Details.class);
10}
11}      

WebClient自定义

WebClient定制有三种主要方法,具体取决于您希望应用的范围。

为了尽可能缩小任何自定义的范围,请注入自动配置 WebClient.Builder,然后根据需要调用其方法。WebClient.Builder实例是有状态的:构建器上的任何更改都会反映在随后用它创建的所有客户端中。如果您想使用相同的构建器创建多个客户端,则还可以考虑使用克隆构建器WebClient.Builder other = builder.clone();。

继续阅读