可以使用这个方法试试 设置长时间保持策略
伪代码
/** * 配置长连接保持策略 * * @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(httpClientPoolConfig.getKeepAliveTargetHost()).orElseGet(HashMap::new) .entrySet().stream().filter( e -> e.getKey().equalsIgnoreCase(target.getHostName())).findAny(); //否则使用默认长连接保持时间 return any.map(en -> en.getValue() * 1000L).orElse(httpClientPoolConfig.getKeepAliveTime() * 1000L); }; }
调用 根据自己实际的连接方式来 这里只是设置了其中一个参数
RestClientBuilder builder = RestClient.builder(httpHosts).setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectTimeout(5000); requestConfigBuilder.setSocketTimeout(40000); requestConfigBuilder.setConnectionRequestTimeout(1000); return requestConfigBuilder; }); if (null != username && null != password) { final CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); builder.setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.disableAuthCaching(); httpClientBuilder.setDefaultCredentialsProvider(provider); httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy()); return httpClientBuilder; }); }
标签:requestConfigBuilder,return,请求,httpClientBuilder,new,JAVA,连接,he From: https://www.cnblogs.com/pxblog/p/18158527