標籤:err ESS alived div asi war 訊息 pos eth
package cn.com.cfets.imt.impl.spring.util;import org.apache.http.HeaderElement;import org.apache.http.HeaderElementIterator;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.conn.ConnectionKeepAliveStrategy;import org.apache.http.entity.ByteArrayEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicHeaderElementIterator;import org.apache.http.protocol.HTTP;import org.apache.http.protocol.HttpContext;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.StringUtils;import java.io.IOException;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;import java.util.Map;/** * 串連池 * Created by fenglei.ma on 2018/5/23. 17:54 */public class HttpClientUtils { private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class); public static int CONNECT_TIME = 3 * 1000; public static int SOCKET_TIME = 3 * 1000; // 毫秒 public static int REQUEST_TIME = 3 * 1000; // 是否重連 public static String ISRECONN = "N"; // 這裡使用串連池防止高並發大量請求時來提高輸送量 public static PoolingHttpClientConnectionManager cm = null; // 使用預設的httpClient執行個體. public static CloseableHttpClient httpClient = null; // 每個route最大串連數 private static final int count = 32; // 整個串連池的最大串連數 private static final int totalCount = 500; private static final int Http_Default_Keep_Time =15000; public static synchronized void initPools() { if (httpClient == null) { cm = new PoolingHttpClientConnectionManager(); cm.setDefaultMaxPerRoute(count); cm.setMaxTotal(totalCount); // 禁用重新導向 setRedirectsEnabled(Boolean.FALSE) if("Y".equalsIgnoreCase(ISRECONN)){ httpClient = HttpClients.custom().setDefaultRequestConfig( RequestConfig.custom().setRedirectsEnabled(Boolean.FALSE).build() ).setKeepAliveStrategy(defaultStrategy).setConnectionManager(cm).build(); }else if("N".equalsIgnoreCase(ISRECONN) || StringUtils.isEmpty(ISRECONN)){ /** * automaticRetriesDisabled類型是boolean,預設值是false, * 這裡設定為true,禁止重試串連3次 */ httpClient = HttpClients.custom().setDefaultRequestConfig( RequestConfig.custom().setRedirectsEnabled(Boolean.FALSE).build() ).setKeepAliveStrategy(defaultStrategy).setConnectionManager(cm).disableAutomaticRetries().build(); } } } /** * 配置請求的逾時設定 * @param httpRequestBase */ private static void config(HttpRequestBase httpRequestBase) { RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(REQUEST_TIME) .setConnectTimeout(CONNECT_TIME).setSocketTimeout(SOCKET_TIME).build(); httpRequestBase.setConfig(requestConfig); } /** * Http connection keepAlive 設定 */ public static ConnectionKeepAliveStrategy defaultStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); int keepTime = Http_Default_Keep_Time; while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (Exception e) { log.error("format KeepAlive timeout exception, exception:" + e.toString()); } } } return keepTime * 1000; } }; /** * Get 請求 * @param path 請求url * @param jsonParam 請求參數 * @param allHeader 要求標頭 * @return */ public static HttpResponse executeGetMothedRequest(String path, String jsonParam, Map<String, String> allHeader) { HttpGet httpget = null; HttpResponse response = null; try { if (!StringUtils.isEmpty(jsonParam)) { path = path + "?" + jsonParam; log.info(path); } URL url = new URL(path); URI uri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null); httpget = new HttpGet(uri); httpget.setHeader("Content-Type", "application/json"); for (Map.Entry<String, String> e : allHeader.entrySet()) { httpget.setHeader(e.getKey(), e.getValue()); } if(httpClient == null){ initPools(); } config(httpget); response = httpClient.execute(httpget); } catch (Exception e) { log.error(e.getMessage(), e); } return response; } /** * Post 請求 * @param url 請求url * @param body 請求資料 * @param paramJson 請求參數 * @param allHeade 請求訊息頭 * @return */ public static HttpResponse executePostMothedRequest(String url, byte[] body, String paramJson, Map<String, String> allHeade) { HttpPost httppost = null; HttpResponse response = null; try { if (!StringUtils.isEmpty(paramJson)) { url = url + "?" + paramJson; log.info(url); } httppost = new HttpPost(url); // 訊息頭 for (Map.Entry<String, String> e : allHeade.entrySet()) {// httppost.setHeader("Content-Type", "application/json"); httppost.setHeader(e.getKey(), e.getValue()); } // 包含上傳檔案資料 if (!StringUtils.isEmpty(body)) {// httppost.setHeader("Content-Type", "application/json"); httppost.setEntity(new ByteArrayEntity(body)); } if(httpClient == null){ initPools(); } config(httppost); response = httpClient.execute(httppost); if (response.getStatusLine().getStatusCode() >= 400) { log.warn("Failed : HTTP error code :" + response.getStatusLine().getStatusCode()); } } catch (Exception e) { log.error(e.getMessage(), e); } return response; }}
HttpClient串連池