@Configuration @EnableConfigurationProperties({HttpClientConfigProperties.class}) @ConditionalOnClass({RestTemplate.class}) @Slf4j public class RestTemplateConfig { @Autowired HttpClientConfigProperties httpClientConfigProperties;
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
@Bean("customShuShuoRestTemplate") public RestTemplate customRestTemplate(ClientHttpRequestFactory httpRequestFactory) { RestTemplate restTemplate = new RestTemplate(httpRequestFactory); List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters(); HttpMessageConverter<?> converterTarget = null; for (HttpMessageConverter<?> item : converterList) { if (StringHttpMessageConverter.class == item.getClass()) { converterTarget = item; break; } } if (null != converterTarget) { converterList.remove(converterTarget); } Charset defaultCharset = Charset.forName(httpClientConfigProperties.getCharSet()); converterList.add(1, new StringHttpMessageConverter(defaultCharset)); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); List<ClientHttpRequestInterceptor> clientHttpRequestInterceptors = new LinkedList<>(); clientHttpRequestInterceptors.add(new HttpSendInterceptor()); restTemplate.setInterceptors(clientHttpRequestInterceptors); return restTemplate; }
@Bean public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) { ConfigCheckUtils.checkHttpClientConfig(httpClientConfigProperties); HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); httpComponentsClientHttpRequestFactory.setHttpClient(httpClient); httpComponentsClientHttpRequestFactory.setReadTimeout(httpClientConfigProperties.getConnReadTimeOut()); httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(httpClientConfigProperties.getPoolConnReqTimeOut()); httpComponentsClientHttpRequestFactory.setConnectTimeout(httpClientConfigProperties.getConnTimeOut()); return httpComponentsClientHttpRequestFactory; }
@Bean public HttpClientConnectionManager poolingHttpClientConnectionManager() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", createSslConnectionFactory()) .build(); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientConfigProperties.getPerRouterMaxConn()); poolingHttpClientConnectionManager.setMaxTotal(httpClientConfigProperties.getPoolMaxTotalConn()); return poolingHttpClientConnectionManager; }
@Bean public HttpClient httpClient(HttpClientConnectionManager httpClientConnectionManager) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setConnectionManager(httpClientConnectionManager); httpClientBuilder.setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE); httpClientBuilder.setDefaultHeaders(defaultHeaders()); httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy()); return httpClientBuilder.build(); }
@Bean public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() { return (response, context) -> { HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); log.info("HeaderElement:{}", JSON.toJSONString(he)); String param = he.getName(); String value = he.getValue(); if (value != null && "timeout".equalsIgnoreCase(param)) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException e) { log.error("解析长连接过期时间异常", e); } } } HttpHost target = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); Optional<Map.Entry<String, Long>> any = Optional.ofNullable(httpClientConfigProperties.getKeepAliveTargetHost()).orElseGet(HashMap::new) .entrySet().stream().filter( e -> e.getKey().equalsIgnoreCase(target.getHostName())).findAny(); return any.map(Map.Entry::getValue).orElse(httpClientConfigProperties.getKeepAliveTime()); }; }
private List<Header> defaultHeaders() { ArrayList<Header> headers = new ArrayList<>(); headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0" + ".1293.54")); headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate")); headers.add(new BasicHeader("Accept-Language", "zh-CN,en-US")); headers.add(new BasicHeader("Connection", "Keep-Alive")); headers.add(new BasicHeader("Content-Type", "application/json")); return headers; }
private ConnectionSocketFactory createSslConnectionFactory() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(null, (chain, authType) -> true); SSLContext sslContext = sslContextBuilder.build(); return new SSLConnectionSocketFactory(sslContext, httpClientConfigProperties.getSupportsSslProtocol(), null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); }}
|