Calling REST Services

Spring Boot 提供了几种便捷的方式来调用远程 REST 服务。如果您正在开发非阻塞式反应式应用程序并且您正在使用 Spring WebFlux,那么您可以使用 WebClient。如果您喜欢阻塞式 API,那么您可以使用 RestClient`或 `RestTemplate

Spring Boot provides various convenient ways to call remote REST services. If you are developing a non-blocking reactive application and you’re using Spring WebFlux, then you can use WebClient. If you prefer blocking APIs then you can use RestClient or RestTemplate.

WebClient

如果您在类路径上启用了 Spring WebFlux,我们建议您使用 `WebClient`来调用远程 REST 服务。`WebClient`接口提供了一种函数式风格 API,并且完全响应。您可以在 Spring Framework 文档中的专门 {url-spring-framework-docs}/web/webflux-webclient.html[部分]中了解更多有关 `WebClient`的信息。

If you have Spring WebFlux on your classpath we recommend that you use WebClient to call remote REST services. The WebClient interface provides a functional style API and is fully reactive. You can learn more about the WebClient in the dedicated {url-spring-framework-docs}/web/webflux-webclient.html[section in the Spring Framework docs].

如果您不在编写反应式 Spring WebFlux 应用程序,则可以使用 RestClient代替 WebClient。这提供了类似的函数式 API,但它是阻塞式而不是响应式的。

If you are not writing a reactive Spring WebFlux application you can use the RestClient instead of a WebClient. This provides a similar functional API, but is blocking rather than reactive.

Spring Boot 为您创建并预先配置了原型 `WebClient.Builder`Bean。强烈建议您将其注入到组件中并使用它来创建 `WebClient`实例。Spring Boot 配置该构建器来共享 HTTP 资源并以与服务器资源相同的方式反映编解码器设置(请参见 WebFlux HTTP codecs auto-configuration),以及更多功能。

Spring Boot creates and pre-configures a prototype WebClient.Builder bean for you. It is strongly advised to inject it in your components and use it to create WebClient instances. Spring Boot is configuring that builder to share HTTP resources and reflect codecs setup in the same fashion as the server ones (see WebFlux HTTP codecs auto-configuration), and more.

以下代码显示了一个典型的示例:

The following code shows a typical example:

WebClient Runtime

Spring Boot 会根据应用程序类路径中可用的库自动检测要使用哪个 ClientHttpConnector`来驱动 `WebClient。按偏好的顺序,支持以下客户端:

Spring Boot will auto-detect which ClientHttpConnector to use to drive WebClient depending on the libraries available on the application classpath. In order of preference, the following clients are supported:

  1. Reactor Netty

  2. Jetty RS client

  3. Apache HttpClient

  4. JDK HttpClient

如果类路径上有多个客户端,则将使用最优先的客户端。

If multiple clients are available on the classpath, the most preferred client will be used.

spring-boot-starter-webflux Starter 默认依赖于 io.projectreactor.netty:reactor-netty,它同时提供了服务器和客户端实现。如果您选择使用 Jetty 作为反应式服务器,则应该添加对 Jetty 反应式 HTTP 客户端库 `org.eclipse.jetty:jetty-reactive-httpclient`的依赖。服务器和客户端使用相同的技术有其优势,它会在客户端和服务器之间自动共享 HTTP 资源。

The spring-boot-starter-webflux starter depends on io.projectreactor.netty:reactor-netty by default, which brings both server and client implementations. If you choose to use Jetty as a reactive server instead, you should add a dependency on the Jetty Reactive HTTP client library, org.eclipse.jetty:jetty-reactive-httpclient. Using the same technology for server and client has its advantages, as it will automatically share HTTP resources between client and server.

开发者可以通过提供自定义的 ReactorResourceFactoryJettyResourceFactory bean 来覆盖 Jetty 和 Reactor Netty 的资源配置,这将应用于客户端和服务器。

Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom ReactorResourceFactory or JettyResourceFactory bean - this will be applied to both clients and servers.

如果您希望对客户端覆盖该选择,则可以定义自己的 ClientHttpConnector Bean,并完全控制客户端配置。

If you wish to override that choice for the client, you can define your own ClientHttpConnector bean and have full control over the client configuration.

您可以在 [Spring Framework 参考文档](/web/webflux-webclient/client-builder.html) 中了解有关 WebClient 配置选项的更多信息。

You can learn more about the {url-spring-framework-docs}/web/webflux-webclient/client-builder.html[WebClient configuration options in the Spring Framework reference documentation].

WebClient Customization

共有三种主要方法可以根据您希望自定义范围有多大来进行 WebClient 自定义。

There are three main approaches to WebClient customization, depending on how broadly you want the customizations to apply.

要尽可能缩小任何自定义的范围,请注入自动配置的 WebClient.Builder,然后根据需要调用其方法。WebClient.Builder 实例是有状态的:生成器上的任何更改都会反映在随后使用它创建的所有客户端中。如果您想使用同一个生成器创建多个客户端,也可以考虑使用 WebClient.Builder other = builder.clone(); 克隆生成器。

To make the scope of any customizations as narrow as possible, inject the auto-configured WebClient.Builder and then call its methods as required. WebClient.Builder instances are stateful: Any change on the builder is reflected in all clients subsequently created with it. If you want to create several clients with the same builder, you can also consider cloning the builder with WebClient.Builder other = builder.clone();.

若要对所有 WebClient.Builder 实例进行全应用程序范围内的增加性自定义,您可以声明 WebClientCustomizer Bean,并在注入时在本地更改 WebClient.Builder

To make an application-wide, additive customization to all WebClient.Builder instances, you can declare WebClientCustomizer beans and change the WebClient.Builder locally at the point of injection.

最后,您可以回退到原始 API 并使用 WebClient.create()。在这种情况下,不应用自动配置或 @"14”。

Finally, you can fall back to the original API and use WebClient.create(). In that case, no auto-configuration or WebClientCustomizer is applied.

WebClient SSL Support

如果您需要在 WebClient 使用的 ClientHttpConnector 上进行自定义 SSL 配置,则可以注入一个 WebClientSsl 实例,该实例可与生成器的 apply 方法一起使用。

If you need custom SSL configuration on the ClientHttpConnector used by the WebClient, you can inject a WebClientSsl instance that can be used with the builder’s apply method.

WebClientSsl 接口提供对您在 application.propertiesapplication.yaml 文件中定义的任何 SSL bundles 的访问。

The WebClientSsl interface provides access to any SSL bundles that you have defined in your application.properties or application.yaml file.

以下代码显示了一个典型的示例:

The following code shows a typical example:

RestClient

如果您在应用程序中不使用 Spring WebFlux 或 Project Reactor,我们建议您使用 RestClient 调用远程 REST 服务。

If you are not using Spring WebFlux or Project Reactor in your application we recommend that you use RestClient to call remote REST services.

RestClient 接口提供一个函数式风格的阻塞 API。

The RestClient interface provides a functional style blocking API.

Spring Boot 为您创建并预配置了一个原型 RestClient.Builder Bean。强烈建议您将其注入组件并使用它创建 «26» 实例。Spring Boot 使用 HttpMessageConverters 和一个合适的 ClientHttpRequestFactory 配置该生成器。

Spring Boot creates and pre-configures a prototype RestClient.Builder bean for you. It is strongly advised to inject it in your components and use it to create RestClient instances. Spring Boot is configuring that builder with HttpMessageConverters and an appropriate ClientHttpRequestFactory.

以下代码显示了一个典型的示例:

The following code shows a typical example:

RestClient Customization

共有三种主要方法可以根据您希望自定义范围有多大来进行 RestClient 自定义。

There are three main approaches to RestClient customization, depending on how broadly you want the customizations to apply.

要尽可能缩小任何自定义的范围,请注入自动配置的 RestClient.Builder,然后根据需要调用其方法。RestClient.Builder 实例是有状态的:生成器上的任何更改都会反映在随后使用它创建的所有客户端中。如果您想使用同一个生成器创建多个客户端,也可以考虑使用 RestClient.Builder other = builder.clone(); 克隆生成器。

To make the scope of any customizations as narrow as possible, inject the auto-configured RestClient.Builder and then call its methods as required. RestClient.Builder instances are stateful: Any change on the builder is reflected in all clients subsequently created with it. If you want to create several clients with the same builder, you can also consider cloning the builder with RestClient.Builder other = builder.clone();.

若要对所有 RestClient.Builder 实例进行全应用程序范围内的增加性自定义,您可以声明 RestClientCustomizer Bean,并在注入时在本地更改 RestClient.Builder

To make an application-wide, additive customization to all RestClient.Builder instances, you can declare RestClientCustomizer beans and change the RestClient.Builder locally at the point of injection.

最后,您可以回退到原始 API 并使用 RestClient.create()。在这种情况下,不应用自动配置或 RestClientCustomizer

Finally, you can fall back to the original API and use RestClient.create(). In that case, no auto-configuration or RestClientCustomizer is applied.

RestClient SSL Support

如果您需要在 RestClient 使用的 ClientHttpRequestFactory 上进行自定义 SSL 配置,则可以注入一个 RestClientSsl 实例,该实例可与生成器的 apply 方法一起使用。

If you need custom SSL configuration on the ClientHttpRequestFactory used by the RestClient, you can inject a RestClientSsl instance that can be used with the builder’s apply method.

RestClientSsl 接口提供对您在 application.propertiesapplication.yaml 文件中定义的任何 SSL bundles 的访问。

The RestClientSsl interface provides access to any SSL bundles that you have defined in your application.properties or application.yaml file.

以下代码显示了一个典型的示例:

The following code shows a typical example:

如果您需要在 SSL 捆绑包之外应用其他自定义,可以使用带 ClientHttpRequestFactoriesClientHttpRequestFactorySettings 类:

If you need to apply other customization in addition to an SSL bundle, you can use the ClientHttpRequestFactorySettings class with ClientHttpRequestFactories:

RestTemplate

Spring Framework 的 {url-spring-framework-javadoc}/org/springframework/web/client/RestTemplate.html[RestTemplate] 类早于 RestClient,并且是许多应用程序用于调用远程 REST 服务的经典方式。当您有不想迁移到 RestClient 的现有代码时,或者因为您已经熟悉 RestTemplate API 时,您可能会选择使用 RestTemplate

Spring Framework’s {url-spring-framework-javadoc}/org/springframework/web/client/RestTemplate.html[RestTemplate] class predates RestClient and is the classic way that many applications use to call remote REST services. You might choose to use RestTemplate when you have existing code that you don’t want to migrate to RestClient, or because you’re already familiar with the RestTemplate API.

由于在使用 RestTemplate 实例之前通常需要对其进行自定义,因此 Spring Boot 不会提供任何单个自动配置的 RestTemplate Bean。但是,它确实会自动配置一个 RestTemplateBuilder,在需要时可将其用于创建 RestTemplate 实例。自动配置的 RestTemplateBuilder 可确保对 RestTemplate 实例应用正确的 HttpMessageConverters 和合适的 ClientHttpRequestFactory

Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder, which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder ensures that sensible HttpMessageConverters and an appropriate ClientHttpRequestFactory are applied to RestTemplate instances.

以下代码显示了一个典型的示例:

The following code shows a typical example:

RestTemplateBuilder 包含许多有用的方法,可用于快速配置 RestTemplate。例如,要添加 BASIC 身份验证支持,您可以使用 builder.basicAuthentication("user", "password").build()

RestTemplateBuilder includes a number of useful methods that can be used to quickly configure a RestTemplate. For example, to add BASIC authentication support, you can use builder.basicAuthentication("user", "password").build().

RestTemplate Customization

对于 RestTemplate 自定义,有三种主要方法,这取决于你想要将自定义应用到多广的范围。

There are three main approaches to RestTemplate customization, depending on how broadly you want the customizations to apply.

为了使任何自定义的范围尽可能窄,注入自动配置的 RestTemplateBuilder,然后根据需要调用其方法。每个方法调用都会返回一个新的 RestTemplateBuilder 实例,因此该自定义仅影响构建器的该次调用。

To make the scope of any customizations as narrow as possible, inject the auto-configured RestTemplateBuilder and then call its methods as required. Each method call returns a new RestTemplateBuilder instance, so the customizations only affect this use of the builder.

要进行应用范围广的附加自定义,请使用 RestTemplateCustomizer bean。所有此类 bean 会自动在自动配置的 RestTemplateBuilder 中进行注册,并应用于用其构建的任何模板。

To make an application-wide, additive customization, use a RestTemplateCustomizer bean. All such beans are automatically registered with the auto-configured RestTemplateBuilder and are applied to any templates that are built with it.

以下示例显示了一个自定义器,配置通过代理访问除 192.168.0.5 之外的所有主机:

The following example shows a customizer that configures the use of a proxy for all hosts except 192.168.0.5:

最后,你可以定义自己的 RestTemplateBuilder bean。这样做会替换自动配置的构建器。如果你希望任何 RestTemplateCustomizer bean 应用于你的自定义构建器,就像自动配置所做的那样,使用 RestTemplateBuilderConfigurer 进行配置。以下示例显示了一个 RestTemplateBuilder,它与 Spring Boot 的自动配置相匹配,不同之处在于还指定了自定义连接和读取超时时间:

Finally, you can define your own RestTemplateBuilder bean. Doing so will replace the auto-configured builder. If you want any RestTemplateCustomizer beans to be applied to your custom builder, as the auto-configuration would have done, configure it using a RestTemplateBuilderConfigurer. The following example exposes a RestTemplateBuilder that matches what Spring Boot’s auto-configuration would have done, except that custom connect and read timeouts are also specified:

最极端(且很少使用)的选项是创建你自己的 RestTemplateBuilder bean,而不使用配置器。除了替换自动配置的构建器外,这样还会阻止使用任何 RestTemplateCustomizer bean。

The most extreme (and rarely used) option is to create your own RestTemplateBuilder bean without using a configurer. In addition to replacing the auto-configured builder, this also prevents any RestTemplateCustomizer beans from being used.

RestTemplate SSL Support

如果你需要对 RestTemplate 进行自定义 SSL 配置,可以使用此示例所示,将 SSL bundle 应用于 RestTemplateBuilder

If you need custom SSL configuration on the RestTemplate, you can apply an SSL bundle to the RestTemplateBuilder as shown in this example:

HTTP Client Detection for RestClient and RestTemplate

Spring Boot 会根据应用程序类路径中可用的库自动检测与 RestClientRestTemplate 配合使用哪个 HTTP 客户端。按照下列偏好顺序,支持以下客户端:

Spring Boot will auto-detect which HTTP client to use with RestClient and RestTemplate depending on the libraries available on the application classpath. In order of preference, the following clients are supported:

  1. Apache HttpClient

  2. Jetty HttpClient

  3. OkHttp (deprecated)

  4. Simple JDK client (HttpURLConnection)

如果类路径上有多个客户端,则将使用最优先的客户端。

If multiple clients are available on the classpath, the most preferred client will be used.