Use httpclient connection pool

package com.bltx.sprider.interfaceData;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
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;

/**
 * Thread connection pool
 *
 * @author ljw
 *
 */
public class HttpConnectionManager {

	private static Logger log = LoggerFactory.getLogger(HttpConnectionManager.class);

	static PoolingHttpClientConnectionManager cm = null;

	/*
	 * initialization method
	 */
	@PostConstruct
	public void init() {
		LayeredConnectionSocketFactory sslsf = null;
		
		try {
			sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
		} catch (NoSuchAlgorithmException e) {
			log.error("Algorithm error");
			e.printStackTrace ();
		}
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
		cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		cm.setMaxTotal(500);//Maximum number of connections
		cm.setDefaultMaxPerRoute(40);// Increase the default maximum number of connections per route to 20
		 // Increase the maximum number of connections to the target host
		HttpHost localhost = new HttpHost("13.54.120.185",443);
        cm.setMaxPerRoute(new HttpRoute(localhost), 100);
      
        //HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
		
		new IdleConnectionMonitorThread(cm).start();//Start the thread and clear the failed connection once in 5 seconds  
	
	}
	
	 

	public static CloseableHttpClient getHttpClient() {
		
		//Connection survival strategy
		ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {

	        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
	            // Honor 'keep-alive' header
	            HeaderElementIterator it = new BasicHeaderElementIterator(
	                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
	            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(NumberFormatException ignore) {
	                    }
	                }
	            }
	            HttpHost target = (HttpHost) context.getAttribute(
	                    HttpClientContext.HTTP_TARGET_HOST);	            
	            
	            if ("makeabooking.flyscoot.com".equalsIgnoreCase(target.getHostName())) {
	                // Keep alive for 5 seconds only
	                return 5 * 1000;
	            } else {
	                // otherwise keep alive for 30 seconds
	                return 30 * 1000;
	            }
	        }

	    };
	    
        // request retry processing
        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler()
        {
            public boolean retryRequest(IOException exception,
                    int executionCount, HttpContext context) {
                if (executionCount >= 5) {// If it has retried 5 times, give up
                   
                	log.error("Have retried 5 times, give up");
                	
                	return false;
                }
                if (exception instanceof NoHttpResponseException) {// If the server lost the connection, then try again
                	
                	log.error("Server lost connection");
                	
                	return true;
                }
                if (exception instanceof SSLHandshakeException) {// Do not retry SSL handshake exception
                    
                	log.error("SSL handshake exception");
                	
                	return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    
                	log.error("timeout");
                	
                	return false;
                }
                if (exception instanceof UnknownHostException) {// The target server is unreachable
                   
                	log.error("The target server is unreachable");
                	
                	return false;
                }
                if (exception instanceof ConnectTimeoutException) {// Connection refused
                  
                	log.error("Connection refused");
                	
                	return false;
                }
                if (exception instanceof SSLException) {// SSL handshake exception
                    
                	log.error("SSL exception");
                	
                	return false;
                }

                HttpClientContext clientContext = HttpClientContext
                        .adapt(context);
                HttpRequest request = clientContext.getRequest();
                // If the request is idempotent, try again
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };
		
		// Create an instance of httpclient
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// Automatically handle redirects
		httpClientBuilder.disableAutomaticRetries (). setRedirectStrategy (new LaxRedirectStrategy ());

		HeadMessage.configureHttpClient(httpClientBuilder);// Call directly ignoring the certificate

		CloseableHttpClient httpclient = httpClientBuilder
				.setRetryHandler(httpRequestRetryHandler)
				.setConnectionManager(cm)
				.setKeepAliveStrategy(keepAliveStrategy)
				.build(); // create an instance of httpclient

		return httpclient;
	}  
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326712692&siteId=291194637