Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Carlos Wu
Added: Aug 9, 2018 9:51 AM
Modified: Aug 9, 2018 9:53 AM
Views: 7
Tags: httpclient
  1. package com.drfirst.pdmp.service.util;
  2.  
  3. import org.apache.commons.lang3.BooleanUtils;
  4. import org.apache.commons.lang3.math.NumberUtils;
  5. import org.apache.http.client.config.CookieSpecs;
  6. import org.apache.http.client.config.RequestConfig;
  7. import org.apache.http.config.Registry;
  8. import org.apache.http.config.SocketConfig;
  9. import org.apache.http.conn.socket.ConnectionSocketFactory;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClients;
  12. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  13.  
  14. import javax.annotation.PreDestroy;
  15. import java.util.HashMap;
  16. import java.util.Map;
  17. import java.util.Properties;
  18. import java.util.concurrent.TimeUnit;
  19.  
  20. import static org.apache.commons.lang3.StringUtils.isNotEmpty;
  21.  
  22. /**
  23.  * State HttpClient factory maintain all connection manager by state and registry by service provider
  24.  * User: Carlos
  25.  * Date: 2018/7/4
  26.  */
  27. public class StateHttpClientFactory {
  28.  
  29.     private Properties properties;
  30.     private RequestConfig requestConfig;
  31.     private Map<String, PoolingHttpClientConnectionManager> stateHttpPool = new HashMap<>();
  32.     private Registry<ConnectionSocketFactory> socketFactoryRegistry;
  33.  
  34.     public StateHttpClientFactory(Properties properties, Registry<ConnectionSocketFactory> socketFactoryRegistry) {
  35.         this.properties = properties;
  36.         this.socketFactoryRegistry = socketFactoryRegistry;
  37.     }
  38.  
  39.     private synchronized PoolingHttpClientConnectionManager setup(String statusCode) {
  40.         PoolingHttpClientConnectionManager cm = stateHttpPool.get(statusCode);
  41.         if (cm != null) {
  42.             return cm;
  43.         }
  44.  
  45.         HttpProp prop = new HttpProp(statusCode, properties);
  46.         requestConfig = RequestConfig.custom()
  47.                 .setSocketTimeout(prop.getSoTimeout())
  48.                 .setConnectTimeout(prop.getConnectTimeout())
  49.                 .setConnectionRequestTimeout(prop.getConnectionRequestTimeout())
  50.                 .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
  51.                 .build();
  52.         if (socketFactoryRegistry == null) {
  53.             cm = new PoolingHttpClientConnectionManager(prop.getPoolingMsTimeToLive(), TimeUnit.MILLISECONDS);
  54.         } else {
  55.             cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null, prop.getPoolingMsTimeToLive(), TimeUnit.MILLISECONDS);
  56.         }
  57.  
  58.         cm.setDefaultMaxPerRoute(prop.getPoolingDefaultMaxPerRoute());
  59.         cm.setMaxTotal(prop.getPoolingMaxTotal());
  60.         cm.setDefaultSocketConfig(SocketConfig.custom()
  61.                 .setTcpNoDelay(prop.isTcpNoDelay())
  62.                 .setSoLinger(prop.getLinger())
  63.                 .setSoTimeout(prop.getSoTimeout())
  64.                 .setSndBufSize(prop.getSocketBufferSize())
  65.                 .setRcvBufSize(prop.getSocketBufferSize())
  66.                 .build());
  67.         stateHttpPool.put(statusCode, cm);
  68.         return cm;
  69.     }
  70.  
  71.  
  72.     public CloseableHttpClient getHttpClient(String statusCode) {
  73.         PoolingHttpClientConnectionManager cm = setup(statusCode);
  74.         return HttpClients.custom()
  75.                 .setDefaultRequestConfig(requestConfig)
  76.                 .setConnectionManager(cm)
  77.                 .build();
  78.     }
  79.  
  80.     public PoolingHttpClientConnectionManager getConnectionManager(String statusCode) {
  81.         return stateHttpPool.get(statusCode);
  82.     }
  83.  
  84.     @PreDestroy
  85.     public void shutdown(){
  86.         for (PoolingHttpClientConnectionManager cm : stateHttpPool.values()) {
  87.             cm.close();
  88.         }
  89.     }
  90.  
  91.     public Properties getProperties() {
  92.         return properties;
  93.     }
  94.  
  95.     public void setProperties(Properties properties) {
  96.         this.properties = properties;
  97.     }
  98.  
  99.     class HttpProp {
  100.         private final static String SO_TIMEOUT = "http.soTimeout";
  101.         private final static String CONN_TIMEOUT = "http.connectTimeout";
  102.         private final static String CONN_REQ_TIMEOUT = "http.connectionRequestTimeout";
  103.         private final static String TCP_NO_DELAY = "http.tcpNoDelay";
  104.         private final static String LINGER = "http.linger";
  105.         private final static String SOCKET_BUFFER_SIZE = "http.socketBufferSize";
  106.         private final static String POOLING_TTL = "http.pooling.msTimeToLive";
  107.         private final static String POOLING_MAX_ROUTE = "http.pooling.defaultMaxPerRoute";
  108.         private final static String POOLING_TOTAL = "http.pooling.maxTotal";
  109.  
  110.         int soTimeout, connectTimeout, connectionRequestTimeout, linger, socketBufferSize, poolingDefaultMaxPerRoute, poolingMaxTotal;
  111.         boolean tcpNoDelay;
  112.         long poolingMsTimeToLive;
  113.  
  114.         HttpProp(String state, Properties p) {
  115.             soTimeout = load(state, p, SO_TIMEOUT, 60000);
  116.             connectTimeout = load(state, p, CONN_TIMEOUT, 60000);
  117.             connectionRequestTimeout = load(state, p, CONN_REQ_TIMEOUT, 60000);
  118.             tcpNoDelay = load(state, p, TCP_NO_DELAY, "true");
  119.             linger = load(state, p, LINGER, 0);
  120.             socketBufferSize = load(state, p, SOCKET_BUFFER_SIZE, 32768);
  121.             poolingMsTimeToLive = load(state, p, POOLING_TTL, 60000L);
  122.             poolingDefaultMaxPerRoute = load(state, p, POOLING_MAX_ROUTE, 40);
  123.             poolingMaxTotal = load(state, p, POOLING_TOTAL, 200);
  124.         }
  125.  
  126.         int load(String state, Properties p, String key, int defaultValue) {
  127.             int defaultVal = NumberUtils.toInt(p.getProperty(key), defaultValue);
  128.             if (isNotEmpty(state) && p.containsKey(state + "." + key)) {
  129.                 return NumberUtils.toInt(p.getProperty(state + "." + key), defaultVal);
  130.             }
  131.             return defaultVal;
  132.         }
  133.  
  134.         boolean load(String state, Properties p, String key, String defaultValue) {
  135.             Boolean defaultVal = BooleanUtils.toBoolean(p.getProperty(key, defaultValue));
  136.             if (isNotEmpty(state) && p.containsKey(state + "." + key)) {
  137.                 return BooleanUtils.toBoolean(p.getProperty(state + "." + key, defaultVal.toString()));
  138.             }
  139.             return defaultVal;
  140.         }
  141.  
  142.         long load(String state, Properties p, String key, long defaultValue) {
  143.             long defaultVal = NumberUtils.toLong(p.getProperty(key), defaultValue);
  144.             if (isNotEmpty(state) && p.containsKey(state + "." + key)) {
  145.                 return NumberUtils.toLong(p.getProperty(state + "." + key), defaultVal);
  146.             }
  147.             return defaultVal;
  148.         }
  149.  
  150.         int getSoTimeout() {
  151.             return soTimeout;
  152.         }
  153.  
  154.         int getConnectTimeout() {
  155.             return connectTimeout;
  156.         }
  157.  
  158.         int getConnectionRequestTimeout() {
  159.             return connectionRequestTimeout;
  160.         }
  161.  
  162.         int getLinger() {
  163.             return linger;
  164.         }
  165.  
  166.         int getSocketBufferSize() {
  167.             return socketBufferSize;
  168.         }
  169.  
  170.         int getPoolingDefaultMaxPerRoute() {
  171.             return poolingDefaultMaxPerRoute;
  172.         }
  173.  
  174.         int getPoolingMaxTotal() {
  175.             return poolingMaxTotal;
  176.         }
  177.  
  178.         boolean isTcpNoDelay() {
  179.             return tcpNoDelay;
  180.         }
  181.  
  182.         long getPoolingMsTimeToLive() {
  183.             return poolingMsTimeToLive;
  184.         }
  185.     }
  186. }
  187.  
  188. @Bean(name = "logicoyHttpClientFactory")
  189. public StateHttpClientFactory logicoyHttpClient() throws Exception {
  190.    SSLContext sslContext = SSLContexts.custom().build();
  191.    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
  192.            new String[]{"TLSv1.2"},
  193.            null,
  194.            new NoopHostnameVerifier());
  195.  
  196.    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
  197.            .<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory)
  198.            .build();
  199.  
  200.    Properties properties = loadProperties("${instance.properties}/state-httpclient.properties");
  201.    return new StateHttpClientFactory(properties,socketFactoryRegistry);
  202. }
  203.