> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/34.-calling-rest-services-with-webclient.md).

# 34. 使用WebClient调用REST服务

如果你的类路径上存在Spring WebFlux，你也可以选择使用`WebClient`调用REST服务。与`RestTemplate`相比，`WebClient`更有函数式的感觉,而且完全是响应式的。你可以使用`WebClient.create()`创建你自己的client实例。查看[与WebClient有关的章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#web-reactive-client)。

Spring Boot为你创建并预先配置了这样一个builder。比如，客户端HTTP编解码器会以与服务器端相同的方式被配置好（查看[WebFlux HTTP编解码器的自动配置](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-webflux-httpcodecs)）。

以下是典型的示例：

```java
@Service
public class MyService {

    private final WebClient webClient;

    public MyBean(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://example.org").build();
    }

    public Mono<Details> someRestCall(String name) {
        return this.webClient.get().url("/{name}/details", name)
                        .retrieve().bodyToMono(Details.class);
    }

}
```
