此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cn

配置

创建 a 的最简单方法是通过 static 工厂方法之一:WebClientspring-doc.cn

您还可以与更多选项一起使用:WebClient.builder()spring-doc.cn

例如:spring-doc.cn

WebClient client = WebClient.builder()
		.codecs(configurer -> ... )
		.build();
val webClient = WebClient.builder()
		.codecs { configurer -> ... }
		.build()

构建后, a 是不可变的。但是,您可以克隆它并构建一个 修改副本如下:WebClientspring-doc.cn

WebClient client1 = WebClient.builder()
		.filter(filterA).filter(filterB).build();

WebClient client2 = client1.mutate()
		.filter(filterC).filter(filterD).build();

// client1 has filterA, filterB

// client2 has filterA, filterB, filterC, filterD
val client1 = WebClient.builder()
		.filter(filterA).filter(filterB).build()

val client2 = client1.mutate()
		.filter(filterC).filter(filterD).build()

// client1 has filterA, filterB

// client2 has filterA, filterB, filterC, filterD

最大内存大小

编解码器 memory 以避免应用程序内存问题。默认情况下,这些设置为 256KB。 如果这还不够,您将收到以下错误:spring-doc.cn

org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer

要更改默认编解码器的限制,请使用以下内容:spring-doc.cn

WebClient webClient = WebClient.builder()
		.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024))
		.build();
val webClient = WebClient.builder()
		.codecs { configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024) }
		.build()

Reactor Netty

要自定义 Reactor Netty 设置,请提供预配置的 :HttpClientspring-doc.cn

HttpClient httpClient = HttpClient.create().secure(sslSpec -> ...);

WebClient webClient = WebClient.builder()
		.clientConnector(new ReactorClientHttpConnector(httpClient))
		.build();
val httpClient = HttpClient.create().secure { ... }

val webClient = WebClient.builder()
	.clientConnector(ReactorClientHttpConnector(httpClient))
	.build()

资源

默认情况下,参与 中保存的全局 Reactor Netty 资源,包括事件循环线程和连接池。 这是推荐的模式,因为固定的共享资源是事件循环的首选 并发。在此模式下,全局资源将保持活动状态,直到进程退出。HttpClientreactor.netty.http.HttpResourcesspring-doc.cn

如果服务器与进程定时,则通常不需要显式 关闭。但是,如果服务器可以在进程内启动或停止(例如,Spring MVC 应用程序部署为 WAR),你可以声明一个类型为 with(默认值)的 Spring 管理的 bean,以确保 Reactor 当 Spring 关闭时,netty 全局资源会关闭, 如下例所示:ReactorResourceFactoryglobalResources=trueApplicationContextspring-doc.cn

@Bean
public ReactorResourceFactory reactorResourceFactory() {
	return new ReactorResourceFactory();
}
@Bean
fun reactorResourceFactory() = ReactorResourceFactory()

您也可以选择不参与全局 Reactor Netty 资源。然而 在这种模式下,您有责任确保所有 Reactor Netty 客户端和服务器 实例使用共享资源,如下例所示:spring-doc.cn

@Bean
public ReactorResourceFactory resourceFactory() {
	ReactorResourceFactory factory = new ReactorResourceFactory();
	factory.setUseGlobalResources(false); (1)
	return factory;
}

@Bean
public WebClient webClient() {

	Function<HttpClient, HttpClient> mapper = client -> {
		// Further customizations...
	};

	ClientHttpConnector connector =
			new ReactorClientHttpConnector(resourceFactory(), mapper); (2)

	return WebClient.builder().clientConnector(connector).build(); (3)
}
1 创建独立于全局资源的资源。
2 将构造函数与资源工厂一起使用。ReactorClientHttpConnector
3 将连接器插入 。WebClient.Builder
@Bean
fun resourceFactory() = ReactorResourceFactory().apply {
	isUseGlobalResources = false (1)
}

@Bean
fun webClient(): WebClient {

	val mapper: (HttpClient) -> HttpClient = {
		// Further customizations...
	}

	val connector = ReactorClientHttpConnector(resourceFactory(), mapper) (2)

	return WebClient.builder().clientConnector(connector).build() (3)
}
1 创建独立于全局资源的资源。
2 将构造函数与资源工厂一起使用。ReactorClientHttpConnector
3 将连接器插入 。WebClient.Builder

超时

要配置连接超时:spring-doc.cn

import io.netty.channel.ChannelOption;

HttpClient httpClient = HttpClient.create()
		.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

WebClient webClient = WebClient.builder()
		.clientConnector(new ReactorClientHttpConnector(httpClient))
		.build();
import io.netty.channel.ChannelOption

val httpClient = HttpClient.create()
		.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

val webClient = WebClient.builder()
		.clientConnector(ReactorClientHttpConnector(httpClient))
		.build();

要配置读取或写入超时:spring-doc.cn

import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

HttpClient httpClient = HttpClient.create()
		.doOnConnected(conn -> conn
				.addHandlerLast(new ReadTimeoutHandler(10))
				.addHandlerLast(new WriteTimeoutHandler(10)));

// Create WebClient...
import io.netty.handler.timeout.ReadTimeoutHandler
import io.netty.handler.timeout.WriteTimeoutHandler

val httpClient = HttpClient.create()
		.doOnConnected { conn -> conn
				.addHandlerLast(ReadTimeoutHandler(10))
				.addHandlerLast(WriteTimeoutHandler(10))
		}

// Create WebClient...

要为所有请求配置响应超时,请执行以下操作:spring-doc.cn

HttpClient httpClient = HttpClient.create()
		.responseTimeout(Duration.ofSeconds(2));

// Create WebClient...
val httpClient = HttpClient.create()
		.responseTimeout(Duration.ofSeconds(2));

// Create WebClient...

要为特定请求配置响应超时,请执行以下操作:spring-doc.cn

WebClient.create().get()
		.uri("https://example.org/path")
		.httpRequest(httpRequest -> {
			HttpClientRequest reactorRequest = httpRequest.getNativeRequest();
			reactorRequest.responseTimeout(Duration.ofSeconds(2));
		})
		.retrieve()
		.bodyToMono(String.class);
WebClient.create().get()
		.uri("https://example.org/path")
		.httpRequest { httpRequest: ClientHttpRequest ->
			val reactorRequest = httpRequest.getNativeRequest<HttpClientRequest>()
			reactorRequest.responseTimeout(Duration.ofSeconds(2))
		}
		.retrieve()
		.bodyToMono(String::class.java)

JDK HttpClient

以下示例显示如何自定义 JDK :HttpClientspring-doc.cn

HttpClient httpClient = HttpClient.newBuilder()
    .followRedirects(Redirect.NORMAL)
    .connectTimeout(Duration.ofSeconds(20))
    .build();

ClientHttpConnector connector =
        new JdkClientHttpConnector(httpClient, new DefaultDataBufferFactory());

WebClient webClient = WebClient.builder().clientConnector(connector).build();
val httpClient = HttpClient.newBuilder()
    .followRedirects(Redirect.NORMAL)
    .connectTimeout(Duration.ofSeconds(20))
    .build()

val connector = JdkClientHttpConnector(httpClient, DefaultDataBufferFactory())

val webClient = WebClient.builder().clientConnector(connector).build()

Jetty

以下示例显示如何自定义 Jetty 设置:HttpClientspring-doc.cn

HttpClient httpClient = new HttpClient();
httpClient.setCookieStore(...);

WebClient webClient = WebClient.builder()
		.clientConnector(new JettyClientHttpConnector(httpClient))
		.build();
val httpClient = HttpClient()
httpClient.cookieStore = ...

val webClient = WebClient.builder()
		.clientConnector(JettyClientHttpConnector(httpClient))
		.build();

默认情况下,创建自己的资源 (、 、 )、 它们将保持活动状态,直到进程退出或被调用。HttpClientExecutorByteBufferPoolSchedulerstop()spring-doc.cn

您可以在 Jetty 客户端(和服务器)的多个实例之间共享资源,并且 确保在 Spring 关闭时关闭资源 声明 Spring 管理的 bean 类型为 ,如下例所示 显示:ApplicationContextJettyResourceFactoryspring-doc.cn

@Bean
public JettyResourceFactory resourceFactory() {
	return new JettyResourceFactory();
}

@Bean
public WebClient webClient() {

	HttpClient httpClient = new HttpClient();
	// Further customizations...

	ClientHttpConnector connector =
			new JettyClientHttpConnector(httpClient, resourceFactory()); (1)

	return WebClient.builder().clientConnector(connector).build(); (2)
}
1 将构造函数与资源工厂一起使用。JettyClientHttpConnector
2 将连接器插入 。WebClient.Builder
@Bean
fun resourceFactory() = JettyResourceFactory()

@Bean
fun webClient(): WebClient {

	val httpClient = HttpClient()
	// Further customizations...

	val connector = JettyClientHttpConnector(httpClient, resourceFactory()) (1)

	return WebClient.builder().clientConnector(connector).build() (2)
}
1 将构造函数与资源工厂一起使用。JettyClientHttpConnector
2 将连接器插入 。WebClient.Builder

HttpComponents 组件

以下示例显示如何自定义 Apache HttpComponents 设置:HttpClientspring-doc.cn

HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
clientBuilder.setDefaultRequestConfig(...);
CloseableHttpAsyncClient client = clientBuilder.build();

ClientHttpConnector connector = new HttpComponentsClientHttpConnector(client);

WebClient webClient = WebClient.builder().clientConnector(connector).build();
val client = HttpAsyncClients.custom().apply {
	setDefaultRequestConfig(...)
}.build()
val connector = HttpComponentsClientHttpConnector(client)
val webClient = WebClient.builder().clientConnector(connector).build()