基于spring,简单的http client 连接配置
import com.google.common.collect.Maps; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import javax.annotation.PostConstruct; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Map; @Service public class HttpClient { private Logger logger = LoggerFactory.getLogger(getClass()); private CloseableHttpClient httpClient; @Value("${http.maxTotal:256}") private int maxTotal; // 最大连接数 @Value("${http.defaultMaxPerRoute:20}") private int defaultMaxPerRoute; // 每个路由最大连接 @Value("${http.connectTimeout:3000}") private int connectTimeout; // 连接超时 3秒 @Value("${http.connectionRequestTimeout:500}") private int connectionRequestTimeout; // 从 httpclient 资源池获取httpclient 最多等待500毫秒 @Value("${http.socketTimeout:30000}") private int socketTimeout; // 读取超时 30秒 @Value("${http.validateAfterInactivity:120000}") private int validateAfterInactivity; // 连接闲置2分钟后需要重新检测 @PostConstruct public void initHttpClient() throws IOException { PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(); httpClientConnectionManager.setMaxTotal(maxTotal); httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); httpClientConnectionManager.setValidateAfterInactivity(validateAfterInactivity); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setConnectionManager(httpClientConnectionManager); httpClient = httpClientBuilder.build(); } private RequestConfig.Builder generateConfigBuilder() { RequestConfig.Builder builder = RequestConfig.custom(); builder.setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(connectionRequestTimeout) .setRedirectsEnabled(false) // 配置禁用30x 跳转 .setSocketTimeout(socketTimeout) .build(); return builder; } public String get(final String url) { return get(url, 0); } public String get(final String url, int readTimeOutInMs) { final HttpGet get = new HttpGet(url); final RequestConfig.Builder configBuilder = generateConfigBuilder(); if (readTimeOutInMs > 0) configBuilder.setSocketTimeout(readTimeOutInMs); get.setConfig(configBuilder.build()); CloseableHttpResponse response = null; try { response = httpClient.execute(get); final String ret = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); return ret; } catch (Exception e) { logger.error("get {} error, {}", url, e.getMessage(), e); return null; } finally { try { if (response != null) EntityUtils.consume(response.getEntity()); } catch (IOException ignore) { } } } public String postJson(final String url, final Object obj) { return postJson(url, obj, 0); } public String postJson(final String url, final Object obj, int readTimeOutInMs) { final Map<String, String> headers = Maps.newHashMap(); headers.put("Content-Type", "application/json"); return post(url, JsonUtil.serialize(obj), headers, readTimeOutInMs); } public String postJson(final String url, final Object obj, Map<String, String> headers) { return postJson(url, obj, headers, 0); } public String postJson(final String url, final Object obj, Map<String, String> headers, int readTimeOutInMs) { headers.put("Content-Type", "application/json"); return post(url, JsonUtil.serialize(obj), headers, readTimeOutInMs); } public String post(final String url, final String body) { return post(url, body, null, 0); } public String post(final String url, final String body, int readTimeOutInMs) { return post(url, body, null, readTimeOutInMs); } public String post(final String url, final String body, Map<String, String> headers) { return post(url, body, headers, 0); } public String post(final String url, final String body, Map<String, String> headers, int readTimeOutInMs) { final HttpPost post = new HttpPost(url); final RequestConfig.Builder configBuilder = generateConfigBuilder(); if (readTimeOutInMs > 0) configBuilder.setSocketTimeout(readTimeOutInMs); post.setConfig(configBuilder.build()); post.setEntity(new StringEntity(body, StandardCharsets.UTF_8)); if (!CollectionUtils.isEmpty(headers)) headers.forEach((k, v) -> post.addHeader(k, v)); CloseableHttpResponse response = null; try { response = httpClient.execute(post); final String ret = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); return ret; } catch (Exception e) { logger.error("post {} error, {}", url, e.getMessage(), e); return null; } finally { try { if (response != null) EntityUtils.consume(response.getEntity()); } catch (IOException ignore) { } } } }