调用 REST 服务
原文:https://docs.spring.io/spring-boot/reference/io/rest-client.html (Spring Boot 4.2.0)
Spring Boot 提供多种便捷方式来调用远程 REST 服务。如果正在开发非阻塞响应式应用并使用 Spring WebFlux,可以使用 WebClient。如果更喜欢命令式 API,可以使用 RestClient。
WebClient
如果 classpath 上有 Spring WebFlux,建议使用 WebClient 调用远程 REST 服务。WebClient 提供函数式风格的 API,完全响应式。更多内容请参阅 Spring Framework 文档中的专门章节。
如果不是编写响应式 Spring WebFlux 应用,可以使用
RestClient代替 WebClient。它提供类似的函数式 API,但是命令式而非响应式。
Spring Boot 会创建并预配置一个 prototype 作用域的 WebClient.Builder bean。强烈建议将其注入组件并用它创建 WebClient 实例。Spring Boot 配置的 builder 共享 HTTP 连接器资源。
WebClient Runtime
WebClient 支持多种底层 HTTP 客户端库,包括 Reactor Netty、Jetty 和 JDK HttpClient。Spring Boot 会根据 classpath 自动选择合适的实现。
全局 HTTP 连接器配置
连接器行为可以通过 spring.http.client.* 属性全局配置,例如:
spring.http.client.connect-timeout=5s spring.http.client.read-timeout=5s spring.http.client.follow-redirects=true spring.http.client.factory=jdk
WebClient 定制
可以通过注入 WebClient.Builder 并调用其方法进行定制,也可以定义 WebClientCustomizer bean 进行全局定制。
WebClient SSL 支持
WebClient 的 SSL 通过 spring.http.client.ssl.* 或 SSL bundle 配置。
RestClient
如果应用不使用 Spring WebFlux 或 Project Reactor,建议使用 RestClient 调用远程 REST 服务。RestClient 提供函数式风格的命令式 API。
Spring Boot 会创建并预配置一个 prototype 作用域的 RestClient.Builder bean。强烈建议将其注入组件并用它创建 RestClient 实例。Spring Boot 为该 builder 配置了 HttpMessageConverters 和合适的 ClientHttpRequestFactory。
@Component public class MyService { private final RestClient restClient; public MyService(RestClient.Builder builder) { this.restClient = builder.baseUrl("https://example.com").build(); } public MyResponse call() { return this.restClient.get().uri("/api/data").retrieve().body(MyResponse.class); } }
RestClient 定制
可以通过 RestClientCustomizer bean 全局定制 RestClient。
RestClient SSL 支持
RestClient 的 SSL 同样通过 SSL bundle 或 spring.http.client.ssl.* 属性配置。
RestClient 的 HTTP 客户端检测
Spring Boot 会根据 classpath 自动检测 RestClient 使用的 HTTP 客户端,优先级为:Apache HttpClient、OkHttp、JDK HttpClient 等。
全局 HTTP 客户端配置
可以通过 spring.http.client.* 属性全局配置 HTTP 客户端行为。
API 版本控制
RestClient 和 WebClient 支持通过请求头、查询参数或路径段传递 API 版本,可通过属性配置。
HTTP Service 接口客户端
除了直接使用 RestClient 或 WebClient,还可以使用带注解的 Java 接口调用 HTTP 服务。HTTP Service 接口使用 @HttpExchange 注解定义服务契约,更常见的是使用方法特定的变体(@GetExchange、@PostExchange、@DeleteExchange 等)。
导入 HTTP Service
可以使用 @ImportHttpServices 注解导入 HTTP Service 接口。
Service Client 组
可以将多个 HTTP Service 接口分组,统一配置基础 URL 和连接器。
配置属性
HTTP Service 客户端可以通过 spring.http.services.<name>.* 属性配置。
定制
可以通过 HttpServiceProxyFactoryCustomizer 或自定义 builder 定制 HTTP Service 客户端。
高级配置
高级场景可以通过定义 RestClient.Builder 或 WebClient.Builder bean 并配合 @HttpExchange 接口实现。
对所有 HTTP 客户端应用全局配置
可以通过 spring.http.client.* 和 spring.http.services.* 属性对所有 HTTP 客户端应用全局配置,包括连接超时、读取超时、重定向策略和 SSL。
InetAddress 过滤与 SSRF 防护
Spring Boot 默认为 HTTP 客户端提供 InetAddress 过滤以防止 SSRF(服务器端请求伪造)攻击。可以通过 spring.http.client.filter* 相关属性配置允许的 IP 地址范围。