WebClient在Spring Boot中天然异步响应式,无需@Async或线程池;需引入spring-boot-starter-webflux,配置全局WebClient Bean,服务层返回Mono/Flux,Controller保持响应式链路。

Spring Boot 中用 WebClient 发起异步请求,核心在于它天然基于 Reactor(Mono/Flux),本身就是非阻塞、响应式的,**不需要额外“开启异步”或手动提交线程池**——只要不调用 block(),所有操作默认就是异步的。
依赖要加对
确保项目已引入 WebFlux 支持:
- Maven:
spring-boot-starter-webflux(不是spring-boot-starter-web) - 该 starter 已包含 WebClient 所需全部依赖(如 reactor-netty、spring-web-reactive)
- 无需再单独引
spring-web或配置 Tomcat 线程模型来“支持异步”
推荐方式:注入全局配置的 WebClient Bean
统一管理 baseUrl、超时、连接池、默认头等,避免硬编码和重复创建:
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient() {
return WebClient.builder()
.baseUrl("https://api.example.com")
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024)) // 大响应体支持
.clientConnector(new ReactorClientHttpConnector(
HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.responseTimeout(Duration.ofSeconds(10))
))
.build();
}
}- 这样在 Service 中直接
@Autowired WebClient webClient即可使用 - 连接池、超时、重试等都集中在此处配置,清晰可控
发起真正的异步调用(不阻塞)
关键:返回值保持为 Mono 或 Flux,让调用链全程响应式:
当用户要求为 Java 代码添加注释、修改注释、审查注释、整理注释格式,或要求按照代码注释规范处理 Java 文件时,使用本技能。本技能用于统一生成和维护 Java 类注释模板、按 Git 对比 release 判断版本号、补充每行代码上方中文块注释、调整注释空行规则,并保持 Java 文件 UTF-8 无 BOM 编码。典型触发场景包括:补充类注释、更新 @version、检查 @author 来源、整理行尾注释、把注释放到代码上一行、检查注释是否符合规范、构建前检查 Java 注释风格。
@Service
public class UserService {
private final WebClient webClient;
<pre class="brush:php;toolbar:false;">public UserService(WebClient webClient) {
this.webClient = webClient;
}
public Mono<User> fetchUserById(Long id) {
return webClient
.get()
.uri("/users/{id}", id)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatus::isError, response ->
Mono.error(new RuntimeException("HTTP " + response.statusCode())))
.bodyToMono(User.class);
}}
- 方法返回
Mono<user></user>,调用方(如 Controller)继续用Mono处理,不调block() - 如果需要组合多个异步请求(比如查用户+查订单+查地址),用
Mono.zip()或Flux.concat()等操作符并行或串行编排 - 错误处理用
onStatus、onErrorResume,而非 try-catch
Controller 层也要响应式
若你用的是 Spring WebFlux(推荐),Controller 直接返回 Mono 或 Flux:
@RestController
@RequestMapping("/api")
public class UserController {
private final UserService userService;
<pre class="brush:php;toolbar:false;">public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/user/{id}")
public Mono<ResponseEntity<User>> getUser(@PathVariable Long id) {
return userService.fetchUserById(id)
.map(user -> ResponseEntity.ok().body(user))
.defaultIfEmpty(ResponseEntity.notFound().build());
}}
- 整个链路从 Controller → Service → WebClient 全异步、无线程切换、零阻塞
- 如果项目仍用 Spring MVC(即
spring-boot-starter-web),也可调用 WebClient,但需注意:返回Mono时,Controller 必须声明返回类型为Mono<responseentity>></responseentity>,且底层 Web 容器需支持响应式(Spring Boot 2.0+ 默认支持)
不复杂但容易忽略:WebClient 的异步性来自它的设计范式,不是靠 @Async 注解或线程池切换。写法上坚持返回 Mono/Flux、避免 block、配合 WebFlux 编程模型,就自然获得高并发低资源占用的优势。

















