在 Spring Boot 项目中,WebClient 是 Spring WebFlux 模块提供的非阻塞式 HTTP 客户端,用于高效地调用 RESTful API。相比传统的 RestTemplate,它支持响应式编程,在高并发场景下性能更优。本教程将带你从零开始集成和使用 WebClient,涵盖依赖配置、实例创建、请求构建、响应处理以及通用服务封装。
1. 引入必要依赖
首先,确保你的项目使用 Spring Boot 2.x 或更高版本(推荐 3.x)。在 pom.xml 中添加 spring-boot-starter-webflux 模块,这是核心依赖:
<dependencies>
<!-- Spring WebFlux for WebClient -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- 可选:用于 JSON 处理,如 Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
如果你使用 Gradle,则在 build.gradle 中写入:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'com.fasterxml.jackson.core:jackson-databind'
}
2. 创建 WebClient 实例
WebClient 可以通过 Spring Bean 方式全局配置,也可以直接在代码中创建。为了便于重用和统一配置,推荐使用 Bean 方式。
方式一:通过 Bean 全局配置(推荐)
在配置类中定义 WebClient Bean,设置基础 URL 和默认请求头:
import org.springframework.context.annotation.Bean;
org.springframework.context.annotation.Configuration;
org.springframework.web.reactive.function.client.WebClient;
{
WebClient {
WebClient.builder()
.baseUrl()
.defaultHeader(, )
.build();
}
}

