test

lientHttpRequestFactory.setReadTimeout(httpClientPoolConfig.getReadTimeout()); // 从连接池获取请求连接的超时时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的 clientHttpRequestFactory.setConnectionRequestTimeout(httpClientPoolConfig.getConnectionRequestTimout()); return clientHttpRequestFactory; } /** * 初始化RestTemplate,并加入spring的Bean工厂,由spring统一管理 */ @Bean(name = “httpClientTemplate”) public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return createRestTemplate(factory); } /** * 初始化支持异步的RestTemplate,并加入spring的Bean工厂,由spring统一管理,如果你用不到异步,则无须创建该对象 * 这个类过时了 * @return */ /* @Bean(name = “asyncRestTemplate”) @ConditionalOnMissingBean(AsyncRestTemplate.class) public AsyncRestTemplate asyncRestTemplate(RestTemplate restTemplate) { final Netty4ClientHttpRequestFactory factory = new Netty4ClientHttpRequestFactory(); factory.setConnectTimeout(this.connectionTimeout); factory.setReadTimeout(this.readTimeout); return new AsyncRestTemplate(factory, restTemplate); }*/ /** * 配置httpClient * * @return */ @Bean public HttpClient httpClient() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); try { //设置信任ssl访问 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build(); httpClientBuilder.setSSLContext(sslContext); HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() // 注册http和https请求 .register(“http”, PlainConnectionSocketFactory.getSocketFactory()) .register(“https”, sslConnectionSocketFactory).build(); //使用Httpclient连接池的方式配置(推荐),同时支持netty,okHttp以及其他http框架 PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); // 最大连接数 poolingHttpClientConnectionManager.setMaxTotal(httpClientPoolConfig.getMaxTotalConnect()); // 同路由并发数 poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientPoolConfig.getMaxConnectPerRoute()); //配置连接池 httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager); // 重试次数 httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(httpClientPoolConfig.getRetryTimes(), true)); //设置默认请求头 List<Header> headers = getDefaultHeaders(); httpClientBuilder.setDefaultHeaders(headers); //设置长连接保持策略 httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy()); return httpClientBuilder.build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { log.error(“初始化HTTP连接池出错”, e); } return null; } /** * 配置长连接保持策略 * @return */ public ConnectionKeepAliveStrategy connectionKeepAliveStrategy(){ return (response, context) -> { // Honor ‘keep-alive’ header 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 ignore) { log.error(“解析长连接过期时间异常”,ignore); } } } HttpHost target = (HttpHost) context.getAttribute( HttpClientContext.HTTP_TARGET_HOST); //如果请求目标地址,单独配置了长连接保持时间,使用该配置 Optional<Map.Entry<String, Integer>> any = Optional.ofNullable(httpClientPoolProperties.getKeepAliveTargetHost()).orElseGet(HashMap::new) .entrySet().stream().filter( e -> e.getKey().equalsIgnoreCase(target.getHostName())).findAny(); //否则使用默认长连接保持时间 return any.map(en -> en.getValue() * 1000L).orElse(httpClientPoolProperties.getKeepAliveTime() * 1000L); }; } /** * 设置请求头 * * @return */ private List<Header> getDefaultHeaders() { List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader(“User-Agent”, “Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36”)); headers.add(new BasicHeader(“Accept-Encoding”, “gzip,deflate”)); headers.add(new BasicHeader(“Accept-

发表评论

邮箱地址不会被公开。 必填项已用*标注

相关