package com.cusc.nirvana.user.rnr.fp.common.config;

import lombok.extern.slf4j.Slf4j;
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.Autowired;
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;

import java.util.concurrent.TimeUnit;

/**
 * @author stayAnd
 * @date 2022/4/18
 */
@Configuration
@Slf4j
public class RestTemplateConfig {

	@Autowired
	private HttpPoolConfig httpPoolConstants;

	@Bean
	@LoadBalanced
	public RestTemplate balancedRestTemplateRnrFp() {
		return getRestTemplateRnrFp();
	}

	@Bean
	public RestTemplate noBalanceRestTemplateRnrFp() {
		return getRestTemplateRnrFp();
	}

	public RestTemplate getRestTemplateRnrFp() {
		return new RestTemplate(httpRequestFactoryRnrFp());
	}



	private ClientHttpRequestFactory httpRequestFactoryRnrFp() {
		return new HttpComponentsClientHttpRequestFactory(httpClientRnrFp());
	}

	private HttpClient httpClientRnrFp() {
		Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", PlainConnectionSocketFactory.getSocketFactory())
				.register("https", SSLConnectionSocketFactory.getSocketFactory())
				.build();
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
		//设置整个连接池最大连接数
		connectionManager.setMaxTotal(httpPoolConstants.getMaxTotal());
		//路由是对maxTotal的细分
		connectionManager.setDefaultMaxPerRoute(httpPoolConstants.getDefaultMaxPerRoute());
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(httpPoolConstants.getSocketTimeout())  //返回数据的超时时间
				.setConnectTimeout(httpPoolConstants.getConnectTimeout()) //连接上服务器的超时时间
				.setConnectionRequestTimeout(httpPoolConstants.getConnectionRequestTimeout()) //从连接池中获取连接的超时时间
				.build();
		return HttpClientBuilder.create()
				.setDefaultRequestConfig(requestConfig)
				.setConnectionManager(connectionManager)
				//设置后台线程剔除失效连接
				.evictExpiredConnections().evictIdleConnections(httpPoolConstants.getMaxIdleTime(), TimeUnit.SECONDS)
				.build();
	}



}
