HTTP 客户端

Spring Boot 提供了许多与 HTTP 客户端一起使用的启动器。本节回答了与使用它们相关的问题。

配置 RestTemplate 使用代理

RestTemplate 自定义 中所述,您可以使用 RestTemplateCustomizerRestTemplateBuilder 来构建自定义的 RestTemplate。这是创建配置为使用代理的 RestTemplate 的推荐方法。

代理配置的具体细节取决于所使用的底层客户端请求工厂。

配置基于 Reactor Netty 的 WebClient 使用的 TcpClient

当 Reactor Netty 在类路径上时,基于 Reactor Netty 的 WebClient 会自动配置。要自定义客户端对网络连接的处理,请提供一个 ClientHttpConnector bean。以下示例配置了 60 秒的连接超时,并添加了 ReadTimeoutHandler

  • Java

  • Kotlin

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import reactor.netty.http.client.HttpClient;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ReactorResourceFactory;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;

@Configuration(proxyBeanMethods = false)
public class MyReactorNettyClientConfiguration {

	@Bean
	ClientHttpConnector clientHttpConnector(ReactorResourceFactory resourceFactory) {
		HttpClient httpClient = HttpClient.create(resourceFactory.getConnectionProvider())
				.runOn(resourceFactory.getLoopResources())
				.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000)
				.doOnConnected((connection) -> connection.addHandlerLast(new ReadTimeoutHandler(60)));
		return new ReactorClientHttpConnector(httpClient);
	}

}
import io.netty.channel.ChannelOption
import io.netty.handler.timeout.ReadTimeoutHandler
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.client.reactive.ClientHttpConnector
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.http.client.ReactorResourceFactory
import reactor.netty.http.client.HttpClient

@Configuration(proxyBeanMethods = false)
class MyReactorNettyClientConfiguration {

	@Bean
	fun clientHttpConnector(resourceFactory: ReactorResourceFactory): ClientHttpConnector {
		val httpClient = HttpClient.create(resourceFactory.connectionProvider)
			.runOn(resourceFactory.loopResources)
			.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000)
			.doOnConnected { connection ->
				connection.addHandlerLast(ReadTimeoutHandler(60))
			}
		return ReactorClientHttpConnector(httpClient)
	}

}
请注意使用 ReactorResourceFactory 作为连接提供者和事件循环资源。这确保了为接收请求的服务器和发出请求的客户端有效共享资源。