在SpringBoot中使用RestTemplate詳解
SpringBoot中使用RestTemplate
1、配置文件
# 最大連接數(shù) http.maxTotal=100 # 并發(fā)數(shù) http.defaultMaxPerRoute=20 # 客戶端創(chuàng)建連接超時(shí)時(shí)間 http.connectTimeout=10000 # 從連接池中獲取到連接的最長(zhǎng)時(shí)間 http.connectionRequestTimeout=500 # 服務(wù)端響應(yīng)超時(shí)時(shí)間 http.socketTimeout=30000 # 提交請(qǐng)求前測(cè)試連接是否可用 http.staleConnectionCheckEnabled=true # 可用空閑連接過(guò)期時(shí)間,重用空閑連接時(shí)會(huì)先檢查是否空閑時(shí)間超過(guò)這個(gè)時(shí)間,如果超過(guò),釋放socket重新建立 http.validateAfterInactivity=3000000
2、配置類
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Configuration
@ComponentScan("com.xxx")
@PropertySource(value = {"classpath:/xxx.properties", "classpath:/yyy.properties"}, encoding = "utf-8")
public class XxxConfiguration {
@Value("${http.maxTotal}")
private Integer maxTotal;
@Value("${http.defaultMaxPerRoute}")
private Integer defaultMaxPerRoute;
@Value("${http.connectTimeout}")
private Integer connectTimeout;
@Value("${http.connectionRequestTimeout}")
private Integer connectionRequestTimeout;
@Value("${http.socketTimeout}")
private Integer socketTimeout;
@Value("${http.staleConnectionCheckEnabled}")
private boolean staleConnectionCheckEnabled;
@Value("${http.validateAfterInactivity}")
private Integer validateAfterInactivity;
/**
* @description: Rest模板
* @return: org.springframework.web.client.RestTemplate
* @author: wsdhla
* @date: 2022/06/27 16:34
*/
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(httpRequestFactory());
}
/**
* @description: 請(qǐng)求連接池配置
* @return: org.springframework.http.client.ClientHttpRequestFactory
* @author: wsdhla
* @date: 2022/06/27 16:35
*/
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
/**
* @description: HttpClient
* @return: org.apache.http.client.HttpClient
* @author: wsdhla
* @date: 2022/06/27 16:42
*/
@Bean
public HttpClient httpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout)
.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
headers.add(new BasicHeader("Accept-Language", "zh-CN"));
headers.add(new BasicHeader("Connection", "Keep-Alive"));
headers.add(new BasicHeader("Content-type", "application/json;charset=UTF-8"));
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(poolingHttpClientConnectionManager())
.setDefaultHeaders(headers)
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
.build();
}
/**
* @description: Http連接管理器
* @return: org.apache.http.conn.HttpClientConnectionManager
* @author: wsdhla
* @date: 2022/06/27 16:41
*/
@Bean
public HttpClientConnectionManager poolingHttpClientConnectionManager() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(maxTotal);
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
connectionManager.setValidateAfterInactivity(validateAfterInactivity);
return connectionManager;
}
}3、工具類
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.Map;
@Component
public class RestTemplateUtils {
private static RestTemplate restTemplate;
/**
* POST請(qǐng)求調(diào)用方式
* @param url 請(qǐng)求URL
* @param requestBody 請(qǐng)求參數(shù)體
* @param responseType 返回對(duì)象類型
* @return ResponseEntity 響應(yīng)對(duì)象封裝類
*/
public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType)
throws RestClientException {
return restTemplate.postForEntity(url, requestBody, responseType);
}
@Resource
public void setRestTemplate(RestTemplate restTemplate) {
RestTemplateUtils.restTemplate = restTemplate;
}
}4、具體使用
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("acc-key", acc-key);
JSONObject requestParam = new JSONObject();
requestParam.put("code", code);
requestParam.put("message", message);
HttpEntity<String> requestBody = new HttpEntity<String>(JSON.toJSONString(requestParam), headers);
ResponseEntity<實(shí)體類> resp = RestTemplateUtils.post(url, requestBody, 實(shí)體類.class);RestTemplate默認(rèn)使用Java自帶的HttpURLConnection,沒(méi)有池化,會(huì)有性能問(wèn)題,可以使用HttpClient或者OkHttp
HttpClient示例:
@Configuration
public class HttpClientExtConfig {
@ConditionalOnMissingBean(RestTemplate.class)
@Bean
public RestTemplate restTemplate() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(new PoolingHttpClientConnectionManager())
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate();
}
}<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringBoot手寫(xiě)RestTemplate攔截器鏈,掌控HTTP請(qǐng)求實(shí)踐
- SpringBoot3使用RestTemplate請(qǐng)求接口忽略SSL證書(shū)的問(wèn)題解決
- SpringBoot下使用RestTemplate實(shí)現(xiàn)遠(yuǎn)程服務(wù)調(diào)用的詳細(xì)過(guò)程
- SpringBoot自定義RestTemplate的攔截器鏈的實(shí)戰(zhàn)指南
- SpringBoot利用RestTemplate實(shí)現(xiàn)反向代理
- Springboot之restTemplate配置及使用方式
- SpringBoot使用RestTemplate如何通過(guò)http請(qǐng)求將文件下載到本地
相關(guān)文章
springboot項(xiàng)目中使用docker進(jìn)行遠(yuǎn)程部署的實(shí)現(xiàn)
本文主要介紹了在Spring Boot項(xiàng)目中使用Docker進(jìn)行遠(yuǎn)程部署,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
關(guān)于Jsoup將相對(duì)路徑轉(zhuǎn)為絕對(duì)路徑的方法
這篇文章主要介紹了關(guān)于Jsoup將相對(duì)路徑轉(zhuǎn)為絕對(duì)路徑的方法,jsoup 是一款Java 的HTML解析器,可直接解析某個(gè)URL地址、HTML文本內(nèi)容,需要的朋友可以參考下2023-04-04
Nacos服務(wù)注冊(cè)與發(fā)現(xiàn)原理解讀
Nacos是阿里巴巴開(kāi)源的微服務(wù)組件,支持服務(wù)注冊(cè)、發(fā)現(xiàn)及配置管理,采用客戶端心跳維護(hù)、服務(wù)端推送與長(zhǎng)輪詢同步,結(jié)合健康檢查機(jī)制,實(shí)現(xiàn)高效可靠的微服務(wù)治理2025-08-08
WebSocket整合SSM(Spring,Struts2,Maven)的實(shí)現(xiàn)示例
這篇文章主要介紹了WebSocket整合SSM(Spring,Struts2,Maven)的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
基于logback 實(shí)現(xiàn)springboot超級(jí)詳細(xì)的日志配置
java web 下有好幾種日志框架,比如:logback,log4j,log4j2(slj4f 并不是一種日志框架,它相當(dāng)于定義了規(guī)范,實(shí)現(xiàn)了這個(gè)規(guī)范的日志框架就能夠用 slj4f 調(diào)用)。這篇文章主要介紹了基于logback springboot超級(jí)詳細(xì)的日志配置,需要的朋友可以參考下2019-06-06
Java實(shí)現(xiàn)的時(shí)間戳與date對(duì)象相互轉(zhuǎn)換功能示例
這篇文章主要介紹了Java實(shí)現(xiàn)的時(shí)間戳與date對(duì)象相互轉(zhuǎn)換功能,結(jié)合具體實(shí)例形式分析了java日期與時(shí)間戳類型的表示與轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下2017-06-06

