【五一创作】在SpringBoot中使用RestTemplate

时间:2025-03-01 21:39:05

1、配置文件

# 最大连接数
=100

# 并发数
=20

# 客户端创建连接超时时间
=10000

# 从连接池中获取到连接的最长时间
=500

# 服务端响应超时时间
=30000

# 提交请求前测试连接是否可用
=true

# 可用空闲连接过期时间,重用空闲连接时会先检查是否空闲时间超过这个时间,如果超过,释放socket重新建立
=3000000

2、配置类

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;


@Configuration
@ComponentScan("")
@PropertySource(value = {"classpath:/", "classpath:/"}, encoding = "utf-8")
public class XxxConfiguration {
    @Value("${}")
    private Integer maxTotal;

    @Value("${}")
    private Integer defaultMaxPerRoute;

    @Value("${}")
    private Integer connectTimeout;

    @Value("${}")
    private Integer connectionRequestTimeout;

    @Value("${}")
    private Integer socketTimeout;

    @Value("${}")
    private boolean staleConnectionCheckEnabled;

    @Value("${}")
    private Integer validateAfterInactivity;

    /**
     * @description: Rest模板
     * @return: 
     * @author: wsdhla
     * @date: 2022/06/27 16:34
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(httpRequestFactory());
    }

    /**
     * @description: 请求连接池配置
     * @return: 
     * @author: wsdhla
     * @date: 2022/06/27 16:35
     */
    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    /**
     * @description: HttpClient
     * @return: 
     * @author: wsdhla
     * @date: 2022/06/27 16:42
     */
    @Bean
    public HttpClient httpClient() {
        RequestConfig requestConfig = ()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout)
                .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .build();


        List<Header> headers = new ArrayList<>();
        (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"));
        (new BasicHeader("Accept-Encoding", "gzip,deflate"));
        (new BasicHeader("Accept-Language", "zh-CN"));
        (new BasicHeader("Connection", "Keep-Alive"));
        (new BasicHeader("Content-type", "application/json;charset=UTF-8"));

        return ()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(poolingHttpClientConnectionManager())
                .setDefaultHeaders(headers)
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
                .build();
    }

    /**
     * @description: Http连接管理器
     * @return: 
     * @author: wsdhla
     * @date: 2022/06/27 16:41
     */
    @Bean
    public HttpClientConnectionManager poolingHttpClientConnectionManager() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", ())
                .register("https", ())
                .build();

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        (maxTotal);
        (defaultMaxPerRoute);
        (validateAfterInactivity);

        return connectionManager;
    }
}

3、工具类

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;


@Component
public class RestTemplateUtils {

    private static RestTemplate restTemplate;

    /**
     * POST请求调用方式
     * @param url          请求URL
     * @param requestBody  请求参数体
     * @param responseType 返回对象类型
     * @return ResponseEntity 响应对象封装类
     */
    public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType)
            throws RestClientException {
        return (url, requestBody, responseType);
    }

    @Resource
    public void setRestTemplate(RestTemplate restTemplate) {
         = restTemplate;
    }
}

4、具体使用

HttpHeaders headers = new HttpHeaders();
(MediaType.APPLICATION_JSON);
("acc-key", acc-key);

JSONObject requestParam = new JSONObject();
("code", code);
("message", message);

HttpEntity<String> requestBody = new HttpEntity<String>((requestParam), headers);

ResponseEntity<实体类> resp = (url, requestBody, 实体类.class);


RestTemplate默认使用Java自带的HttpURLConnection,没有池化,会有性能问题,可以使用HttpClient或者OkHttp

HttpClient示例:

@Configuration
public class HttpClientExtConfig {

    @ConditionalOnMissingBean()
    @Bean
    public RestTemplate restTemplate() {
        CloseableHttpClient httpClient = ()
                .setConnectionManager(new PoolingHttpClientConnectionManager())
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        (httpClient);

        return new RestTemplate();
    }
}
<dependency>
    <groupId></groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>