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();  
    }  
}
相关推荐
特立独行的猫A5 小时前
用仓颉语言 cj-tauri 框架,五分钟给娃做了个鸿蒙形近字游戏
java·后端·python
码事漫谈8 小时前
我花了一周时间,看AI公司怎么"管"AI,结果越看越后背发凉
后端
爱学习的程序媛10 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
GISer_Jing10 小时前
Agent核心内容
后端·ai·langchain
budingxiaomoli12 小时前
Spring统一功能处理
java·后端·spring
某鹏12 小时前
网关选型:Go、Java、Graal 谁都不能完胜
后端
用户02478365309713 小时前
从屎山到防线:14 行状态迁移表,给任务系统装上防瞎跳闸门
后端
CQU_JIAKE13 小时前
11.13[体系结构】指标,五级流水线,八级流水线,虚实地址思考
后端
panbook15 小时前
从0到1实现一个分布式时序数据库(三):主从复制、故障检测与切换
后端
上线再说15 小时前
图片从 8.2MB 压到 296KB:我把小程序图片链路的账单拆了一遍
后端