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
| private static final int MAX_CONNECTION = 10; private static final int DEFAULT_MAX_CONNECTION = 5; private static final int CONNECT_TIMEOUT = 2000; private static final int SOCKET_TIMEOUT = 2000; private static final int CONNECTION_REQUEST_TIMEOUT = 500;
private static PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); private static HttpClientBuilder httpBuilder = null;
static{ connManager.setMaxTotal(200); connManager.setDefaultMaxPerRoute(100); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 150); SocketConfig socketConfig = SocketConfig.custom() .setTcpNoDelay(true) .setSoReuseAddress(true) .setSoTimeout(500) .setSoLinger(60) .setSoKeepAlive(true) .build(); connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); MessageConstraints messageConstraints = MessageConstraints.custom() .setMaxHeaderCount(200) .setMaxLineLength(2000) .build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints) .build(); HttpRequestRetryHandler requestRetryHandler = new DefaultHttpRequestRetryHandler(0, false); HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) { return false; } if (exception instanceof InterruptedIOException) { return false; } if (exception instanceof UnknownHostException) { return false; } if (exception instanceof ConnectTimeoutException) { return false; } if (exception instanceof SSLException) { return false; }
HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { return true; }
return false; } }; RequestConfig defaultRequestConfig = RequestConfig .custom() .setConnectTimeout(CONNECT_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setStaleConnectionCheckEnabled(true) .build(); httpBuilder = HttpClients.custom(); httpBuilder.setConnectionManager(connectionManager); }
public static CloseableHttpClient getConnection() { CloseableHttpClient httpClient = httpBuilder.build(); return httpClient; }
|