1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
| @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()); }}
|