SpringBoot之RestTemplate使用Apache的HttpClient连接池

SpringBoot自带的RestTemplate是没有使用连接池的,只是SimpleClientHttpRequestFactory实现了ClientHttpRequestFactory、AsyncClientHttpRequestFactory 2个工厂接口,因此每次调用接口都会创建连接和销毁连接,如果是高并发场景下会大大降低性能。因此,我们可以使用Apache的HttpClient连接池。

pom.xml

复制代码
		<!-- RestTemplate使用Apache的HttpComponentsClientHttpRequestFactory替换掉Spring SimpleClientHttpRequestFactory 以使用Apache HttpClient的连接池。 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

RestTemplate配置类

java 复制代码
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(50);
        connectionManager.setDefaultMaxPerRoute(20);

        RequestConfig requestConfig = RequestConfig
                .custom()
                .setConnectionRequestTimeout(5000) // timeout to get connection from pool
                .setSocketTimeout(5000) // standard connection timeout
                .setConnectTimeout(5000) // standard connection timeout
                .build();

        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig).build();

        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

        return new RestTemplate(requestFactory);
    }

}

调用

java 复制代码
	@Autowired  
	private RestTemplate restTemplate;  
  
	public Res getData(Dto dto) {
		String url = "https://xxx.com/api/xxx";
		//封装请求头参数.
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Content-Type", "application/json;charset=utf-8");
        headers.set("自定义请求头key","自定义请求头value");
		Res res = restTemplate.postForEntity(url, new HttpEntity<>(dto, headers), Res.class).getBody();
    	return res;
	}

注意

在Spring Boot中,RestTemplate已经过时,建议使用更现代的RestTemplateBuilder和WebClient。

使用RestTemplateBuilder

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.reactive.function.client.WebClient;  
  
@Service  
public class HttpClientService {  
  
    private final RestTemplateBuilder restTemplateBuilder;  
  
    @Autowired  
    public HttpClientService(RestTemplateBuilder restTemplateBuilder) {  
        this.restTemplateBuilder = restTemplateBuilder;  
    }  
  
    public String getData(String url) {  
        return restTemplateBuilder.build().getForObject(url, String.class);  
    }
}

使用WebClient自定义连接池

java 复制代码
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.http.HttpMethod;  
import org.springframework.stereotype.Service;  
import org.springframework.web.reactive.function.client.WebClient;  
  
@Service  
public class CustomHttpClientService {  
  
    private final WebClient webClient;  
  
    @Autowired  
    public CustomHttpClientService(@Value("${custom.pool.size:10}") int poolSize) {  
        this.webClient = WebClient.builder()  
                .poolSize(poolSize) // 设置连接池大小等其它参数,这里不在一一赘述。
                .build();  
    }  
  
    public String getData(String url) {  
        return webClient.method(HttpMethod.GET).uri(url).retrieve().bodyToMono(String.class).block();  
    }  
}
相关推荐
weixin_985432113 小时前
Spring Boot 中的 @ConditionalOnBean 注解详解
java·spring boot·后端
猎人everest3 小时前
快速搭建运行Django第一个应用—投票
后端·python·django
一只爱撸猫的程序猿5 小时前
创建一个基于Spring AI的智能旅行简单案例
spring boot·程序员·aigc
啾啾Fun5 小时前
精粹汇总:大厂编程规范(持续更新)
后端·规范
yt948325 小时前
lua读取请求体
后端·python·flask
IT_10246 小时前
springboot从零入门之接口测试!
java·开发语言·spring boot·后端·spring·lua
汪子熙6 小时前
在 Word 里编写 Visual Basic 调用 DeepSeek API
后端·算法·架构
寻月隐君7 小时前
手把手教你用 Solana Token-2022 创建支持元数据的区块链代币
后端·web3·github
陌殇殇7 小时前
Hadoop 002 — HDFS常用命令及SpringBoot整合操作
hadoop·spring boot·hdfs