当前位置: 首页 > news >正文

Spring WebFlux 与 WebClient 使用指南


Spring WebFlux 与 WebClient 使用指南


目录

  1. WebClient 概述
  2. 核心依赖配置
  3. WebClient 的创建与配置
  4. 发送 HTTP 请求
    • GET 请求
    • POST 请求
  5. 错误处理
    • HTTP 错误处理 (onStatus)
    • 非 HTTP 错误处理 (doOnError)
  6. 同步与异步调用
    • subscribe()block() 的区别
  7. 统一响应结构
  8. 日志与监控
  9. 高级配置
    • 超时与重试
    • 连接池管理
  10. 常见问题与最佳实践

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 {@Beanpublic 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").build().toUriString();return webClient.post().uri(uri).header("Token-Test", token).bodyValue(users).retrieve().onStatus(HttpStatus::isError, response -> response.bodyToMono(String.class).flatMap(errorBody -> Mono.error(new ServiceException("HTTP错误: " + errorBody)))).bodyToMono(String.class).map(ApiResponse::success).onErrorResume(e -> Mono.just(ApiResponse.error(500, e.getMessage())));
}

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

http://www.xdnf.cn/news/422857.html

相关文章:

  • Linux513 rsync本地传输 跨设备传输 一
  • 原型和原型链
  • list基础用法
  • API安全
  • 【PmHub后端篇】PmHub中基于自定义注解和AOP的服务接口鉴权与内部认证实现
  • 【fastadmin开发实战】在前端页面中使用bootstraptable以及表格中实现文件上传
  • 我的五周年创作纪念日
  • 系统稳定性之上线三板斧
  • 嵌入式开发学习日志(数据结构--顺序结构单链表)Day19
  • upload-labs通关笔记-第4关 文件上传之.htacess绕过
  • Spring Boot 应用中实现基本的 SSE 功能
  • 鸿蒙 核心与非核心装饰器
  • [Java实战]Spring Boot 3 整合 Ehcache 3(十九)
  • Python慕课学习记录报告
  • c# UTC 时间赋值注意事项
  • Linux:进程控制2
  • 医疗实时操作系统方案:手术机器人的微秒级运动控制
  • 单反和无反(私人笔记)
  • 高并发系统设计需要考虑哪些问题
  • 极限学习机进行电厂相关数据预测
  • 目标检测任务常用脚本1——将YOLO格式的数据集转换成VOC格式的数据集
  • 滑动窗口——水果成篮
  • 正则表达式常用验证(一)
  • vim,gcc/g++,makefile,cmake
  • 如何用URDF文件构建机械手模型并与MoveIt集成
  • 获取accesstoken时,提示证书解析有问题,导致无法正常获取token
  • do while
  • 从代码学习深度学习 - 全卷积神经网络 PyTorch版
  • 【网络编程】七、详解HTTP 搭建HTTP服务器
  • MySQL 5.7在CentOS 7.9系统下的安装(上)——以rpm包的形式下载mysql