package com.chenyang.nse.bussiness.kms.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(
   proxyBeanMethods = false
)
@ConditionalOnClass({HttpClient.class})
@ConditionalOnMissingBean({HttpClient.class})
@ConditionalOnProperty(
   name = {"httpclient.enable"},
   havingValue = "true",
   matchIfMissing = true
)
@EnableConfigurationProperties({HttpClientProperties.class})
public class HttpClientAutoConfiguration {
   @Bean(
      destroyMethod = "close"
   )
   public CloseableHttpClient httpClient(HttpClientProperties props) {
      RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(props.getConnectionRequestTimeout()).setConnectTimeout(props.getConnectTimeout()).setSocketTimeout(props.getSocketTimeout()).build();
      return HttpClients.custom().setMaxConnTotal(props.getMaxConnTotal()).setMaxConnPerRoute(props.getMaxConnTotal()).setDefaultRequestConfig(requestConfig).build();
   }
}
