Spring WebFlux 与 WebClient 使用指南及最佳实践

 更新时间:2025年07月03日 15:47:15   作者:千层冷面  
WebClient是Spring WebFlux模块提供的非阻塞、响应式HTTP客户端,基于Project Reactor实现,适用于高并发场景spring webclient,本文给大家介绍Spring WebFlux与WebClient使用指南及最佳实践,感兴趣的朋友一起看看吧

Spring WebFlux 与 WebClient 使用指南

1. WebClient 概述

WebClient 是 Spring WebFlux 模块提供的非阻塞、响应式 HTTP 客户端,基于 Project Reactor 实现,适用于高并发场景。
核心优势

  • 支持异步非阻塞 I/O,提升吞吐量。
  • 链式 API 设计,便于组合操作。
  • 集成 Spring 生态,支持自动编解码(JSON、XML)。

2. 核心依赖配置

pom.xml 中添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

3. WebClient 的创建与配置

3.1 全局配置(推荐)

@Configuration
public class WebClientConfig {
    @Bean
    public WebClient webClient() {
        return WebClient.builder()
            .baseUrl("https://api.example.com") // 基础 URL
            .defaultHeader("Accept", "application/json")
            .clientConnector(new ReactorClientHttpConnector(
                HttpClient.create()
                    .responseTimeout(Duration.ofSeconds(30)) // 响应超时
            )
            .build();
    }
}

3.2 临时创建(按需使用)

WebClient client = WebClient.create("https://api.example.com");

4. 发送 HTTP 请求

4.1 GET 请求(携带 Token)

public Mono<User> getUser(String id, String token) {
    return webClient.get()
        .uri("/users/{id}", id) // 路径参数
        .header("Token-Test", token) // 自定义 Token
        .retrieve()
        .bodyToMono(User.class); // 解析为对象
}

4.2 POST 请求(发送数组 Body)

public Mono<String> postUsers(List<User> users, String token) {
    return webClient.post()
        .uri("/users/batch")
        .header("Token-Test", token)
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(users) // 发送 List 集合
        .retrieve()
        .bodyToMono(String.class);
}

5. 错误处理

5.1 HTTP 错误处理(onStatus)

.onStatus(HttpStatus::isError, response ->
    response.bodyToMono(String.class)
        .flatMap(errorBody -> {
            String msg = String.format("状态码: %d, 错误信息: %s", 
                response.rawStatusCode(), errorBody);
            log.error(msg);
            return Mono.error(new ServiceException(msg));
        })
)

5.2 非 HTTP 错误处理(doOnError)

.doOnError(error -> {
    if (!(error instanceof ServiceException)) {
        log.error("非 HTTP 错误: {}", error.getMessage());
    }
})

6. 同步与异步调用

6.1 异步调用(subscribe)

webClient.get()
    .uri("/data")
    .retrieve()
    .bodyToMono(String.class)
    .subscribe(
        data -> log.info("成功: {}", data),
        error -> log.error("失败: {}", error)
    );

6.2 同步调用(block,仅用于测试或特殊场景)

try {
    String result = webClient.get()
        .uri("/data")
        .retrieve()
        .bodyToMono(String.class)
        .block(Duration.ofSeconds(10)); // 阻塞等待
} catch (Exception e) {
    log.error("请求失败", e);
}

7. 统一响应结构

7.1 定义统一响应类

public class ApiResponse<T> {
    private int code;
    private String message;
    private T data;
    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<>(200, "Success", data);
    }
    public static <T> ApiResponse<T> error(int code, String message) {
        return new ApiResponse<>(code, message, null);
    }
}

7.2 转换响应

public Mono<ApiResponse<User>> getUser(String id) {
    return webClient.get()
        .uri("/users/{id}", id)
        .retrieve()
        .bodyToMono(User.class)
        .map(ApiResponse::success) // 包装为成功响应
        .onErrorResume(e -> 
            Mono.just(ApiResponse.error(500, e.getMessage()))
        );
}

8. 日志与监控

8.1 成功日志

.doOnSuccess(response -> 
    log.info("请求成功: {}", response)
)

8.2 错误日志

.doOnError(error -> 
    log.error("请求失败: {}", error.getMessage())
)

9. 高级配置

9.1 超时与重试

.clientConnector(new ReactorClientHttpConnector(
    HttpClient.create()
        .responseTimeout(Duration.ofSeconds(30)) // 响应超时
)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) // 指数退避重试

9.2 连接池配置

HttpClient.create()
    .baseUrl("https://api.example.com")
    .tcpConfiguration(tcpClient -> 
        tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
    )

10. 常见问题与最佳实践

10.1 避免手动调用subscribe

  • 错误示例
    // Service 层中手动调用 subscribe(不推荐)
    public void sendData() {
        webClient.post().subscribe(); // 可能导致资源泄漏
    }
  • 正确做法
    在 Controller 或调用方返回 Mono/Flux,由框架处理订阅。

10.2 统一异常处理

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Mono<ApiResponse<?>> handleServiceException(ServiceException e) {
        return Mono.just(ApiResponse.error(500, e.getMessage()));
    }
}

10.3 性能优化

  • 复用 WebClient 实例:避免频繁创建新实例。
  • 合理设置超时:根据接口 SLA 调整响应和连接超时。

附录:完整代码示例

发送 POST 请求并处理错误

public Mono<ApiResponse<String>> syncData(List<User> users, String token) {
    String uri = UriComponentsBuilder.fromUriString("https://api.example.com")
        .path("/batch")
        .queryParam("source", "web")
        .queryParamIfPresent("type", Optional.ofNullable("test".equals(activeProfile) ? "test" : null))
        .build()
        .toUriString();
    return webClient.post()
        .uri(uri)
        .header("Token-Test", token)
        .headers(headers -> {
             if ("test".equals(activeProfile)) {
                 headers.add("type", "test"); // 仅测试环境添加
             }
         })
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(users)
        .retrieve()
        .onStatus(HttpStatus::isError, response ->
                response.bodyToMono(String.class)
                        .flatMap(error -> {
                            String msg = String.format("状态码:%d, 错误信息: %s", response.rawStatusCode(), error);
                            log.error(msg);
                            return Mono.error(new RuntimeException(msg));
                        })
        )
        .bodyToMono(ApiResponse.class)  // 解析为自定义响应对象
         // 检查业务状态码
        .flatMap(result -> {
            if (result.getStatusCode() != 200) {
                String msg = String.format("业务错误: code=%d, message=%s",
                        result.getStatusCode(), result.getMessage());
                log.error(msg);
                return Mono.error(new ServiceException(msg));
            }
            return Mono.just(result);
        })
         // 成功记录日志
        .doOnSuccess(success -> log.info("请求成功"))
         // 失败记录日志
        .doOnError(error -> log.error("失败", error.getMessage()))
        .onErrorResume(e -> 
           Mono.just(ApiResponse.error(500, e.getMessage()))
        );
}

通过本文档,您可全面掌握 WebClient 的核心用法、错误处理策略及性能优化技巧。建议结合项目需求灵活调整配置,遵循响应式编程最佳实践。

到此这篇关于Spring WebFlux 与 WebClient 使用指南及最佳实践的文章就介绍到这了,更多相关Spring WebFlux WebClient 使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中csv文件读写超详细分析

    Java中csv文件读写超详细分析

    CSV是一种通用的、相对简单的文件格式,其文件以纯文本形式存储表格数据,下面这篇文章主要给大家介绍了关于Java中csv文件读写分析的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • Spring Boot中获取request的三种方式及请求过程

    Spring Boot中获取request的三种方式及请求过程

    这篇文章主要介绍了Spring Boot当中获取request的三种方式,包括请求过程流程分析及response常用API,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-03-03
  • hibernate一对多关联映射学习小结

    hibernate一对多关联映射学习小结

    这篇文章主要介绍了hibernate一对多关联映射学习小结,需要的朋友可以参考下
    2017-09-09
  • springboot 接收LocalDateTime方式

    springboot 接收LocalDateTime方式

    这篇文章主要介绍了springboot 接收LocalDateTime方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • JavaFX程序初次运行创建数据库并执行建表SQL详解

    JavaFX程序初次运行创建数据库并执行建表SQL详解

    这篇文章主要介绍了JavaFX程序初次运行创建数据库并执行建表SQL详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • Springboot实现通用Auth认证的几种方式

    Springboot实现通用Auth认证的几种方式

    本文主要介绍了Springboot实现通用Auth认证的几种方式,主要介绍了4种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • Java 实例解析单例模式

    Java 实例解析单例模式

    单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式,这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建
    2021-11-11
  • IDEA中配置多个版本的JDK的实现示例

    IDEA中配置多个版本的JDK的实现示例

    IDEA可以配置多个JDK,根据需要使用不同版本的,本文就来介绍一下IDEA中配置多个版本的JDK的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2024-03-03
  • Java集合继承体系详解

    Java集合继承体系详解

    这篇文章主要为大家详细介绍了Java集合继承体系,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • idea两侧的maven-project-structure图标不见了如何解决

    idea两侧的maven-project-structure图标不见了如何解决

    这篇文章主要介绍了如何解决idea两侧的maven-project-structure图标不见了问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07

最新评论