restTemplate 配置连接池、使用map进行传参和设置headers

1.通过HttpClient配置连接池

package com.kittlen.cloud.config;

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.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
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;

/**
 * @author kittlen
 * @version 1.0
 * @date 2021/2/22 13:28
 */
@Configuration
public class RestTemplateConfig{

    @Value("${restTemplate.maxTotal:200}")
    int maxTotal;

    @Value("${restTemplate.defaultMaxPerRoute:100}")
    int defaultMaxPerRoute;

    @Value("${restTemplate.socketTimeout:10000}")
    int socketTimeout;

    @Value("${restTemplate.connectTimeout:5000}")
    int connectTimeout;

    @Value("${restTemplate.connectionRequestTimeout:1000}")
    int connectionRequestTimeout;

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
        restTemplate.getInterceptors().add(new HttpInterceptor());
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        //设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(maxTotal);
        //路由是对maxTotal的细分,单个请求的最大连接数
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout) //服务器返回数据(response)的时间,超过该时间抛出read timeout
                .setConnectTimeout(connectTimeout)//连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
                .setConnectionRequestTimeout(connectionRequestTimeout)//从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}

2.使用map进行传参并添加headers

/**
     * 使用map进行传值
     *
     * @return
     */
    @PostMapping("/byMap")
    public Result<List<Test>> byMap() {
        //设置请求的参数
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("author", "kittlen");
        //设置请求头
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add(HttpHeaders.ACCEPT, "application/json");//*设置期望的接收数据类型,在使用exchange进行制定数据类型,进行数据获取时至关重要(默认为xml方式)
        try {
            ResponseEntity<Result<List<Test>>> exchange = restTemplate.exchange(HTTP + "/test/getTestAll", HttpMethod.POST,
                    new HttpEntity<>(map, headers), new ParameterizedTypeReference<Result<List<Test>>>() {
                    });
            return exchange.getBody();
        } catch (Exception e) {
            return Result.error();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值