Java 类org.apache.http.impl.conn.PoolingHttpClientConnectionManager 实例源码

项目:framework    文件:HttpClientUtil.java   
@PostConstruct
public void afterPropertiesSet() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();

    schemeRegistry.register("http", PlainConnectionSocketFactory.getSocketFactory());

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(new KeyManager[0], new TrustManager[]{new SimpleTrustManager()}, null);
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext);
    schemeRegistry.register("https", sf);

    pool = new PoolingHttpClientConnectionManager(schemeRegistry.build());
    pool.setMaxTotal(maxConnection);
    pool.setDefaultMaxPerRoute(maxConnection);
    pool.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(sotimeout).build());
}
项目:yacy_grid_mcp    文件:ClientConnection.java   
public static PoolingHttpClientConnectionManager getConnctionManager(){

        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                        new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory> create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory)
                    .build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Data.logger.warn("", e);
        }

        PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? 
                new PoolingHttpClientConnectionManager(socketFactoryRegistry):
                new PoolingHttpClientConnectionManager();

        // twitter specific options
        cm.setMaxTotal(2000);
        cm.setDefaultMaxPerRoute(200);

        return cm;
    }
项目:qonduit    文件:HTTPStrictTransportSecurityIT.java   
@Test
public void testHttpRequestGet() throws Exception {

    RequestConfig.Builder req = RequestConfig.custom();
    req.setConnectTimeout(5000);
    req.setConnectionRequestTimeout(5000);
    req.setRedirectsEnabled(false);
    req.setSocketTimeout(5000);
    req.setExpectContinueEnabled(false);

    HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
    get.setConfig(req.build());

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(5);

    HttpClientBuilder builder = HttpClients.custom();
    builder.disableAutomaticRetries();
    builder.disableRedirectHandling();
    builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionManager(cm);
    CloseableHttpClient client = builder.build();

    String s = client.execute(get, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(301, response.getStatusLine().getStatusCode());
            return "success";
        }

    });
    assertEquals("success", s);

}
项目:openssp    文件:DefaultConnector.java   
/**
 * 
 */
public DefaultConnector() {
    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.closeIdleConnections(120, TimeUnit.SECONDS);

    // would be nice to set this from outside -> keep alive
    final SocketConfig sConfig = SocketConfig.custom().setSoKeepAlive(true).setSoTimeout(Context.SOCKET_TO).build();
    cm.setDefaultSocketConfig(sConfig);

    cm.setMaxTotal(150);
    cm.setDefaultMaxPerRoute(150);
    cm.setValidateAfterInactivity(0);

    final HttpRequestRetryHandler rh = new DefaultHttpRequestRetryHandler(3, true);
    httpClient = HttpClients.custom().setRetryHandler(rh).setConnectionManager(cm).build();
}
项目:TITAN    文件:HttpConnectionManager.java   
public void init() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        /* 配置同时支持 HTTP 和 HTPPS */
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
        /* 初始化连接管理器 */
        poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        poolConnManager.setMaxTotal(maxTotal);
        poolConnManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        httpClient = getConnection();
        log.info("HttpConnectionManager初始化完成...");
    } catch (Exception e) {
        log.error("error", e);
    }
}
项目:ts-benchmark    文件:HttpTest.java   
public static void test(){
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // Increase max total connection to 200  
        cm.setMaxTotal(200);  
        // Increase default max connection per route to 20  
        cm.setDefaultMaxPerRoute(20);  
        // Increase max connections for localhost:80 to 50  
        HttpHost localhost = new HttpHost("http://cc.0071515.com", 80);  
        cm.setMaxPerRoute(new HttpRoute(localhost), 2);  

//      CloseableHttpClient httpClient = HttpClients.custom()  
//              .setConnectionManager(cm)  
//              .build();  
        httpClient = HttpClients.custom()  
                .setConnectionManager(cm)  
                .build();  
    }
项目:graphium    文件:CurrentGraphVersionCacheImpl.java   
protected CloseableHttpClient createDefaultHttpClient() {

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxConnections);
    cm.setDefaultMaxPerRoute(maxConnections);

   Builder config = RequestConfig.custom()
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout);

      // TODO: Set Credentials
    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(cm).setDefaultRequestConfig(config.build())
            .build();
    return httpClient;      
}
项目:Auts_Assert_manager    文件:PhicommHttpClient.java   
public static String httpsGet(String getUrl, String defaultCharset, Map<String, String> headerParas)
        throws KeyManagementException, NoSuchAlgorithmException {
    // 采用绕过验证的方式处理https请求
    SSLContext sslcontext = createIgnoreVerifySSL();

    // 设置协议http和https对应的处理socket链接工厂的对象
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);

    // 创建自定义的httpclient对象
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).build();

    return getInner(getUrl, defaultCharset, headerParas, httpclient);
}
项目:illuminati    文件:IlluminatiHttpClient.java   
private void initPoolingHttpClientManager () {
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", SSLConnectionSocketFactory.getSocketFactory())
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(MAX_CONNECTION);
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT);

    final RequestConfig requestConfig = requestConfigBuilder.build();

    HashSet<Header> defaultHeaders = new HashSet<Header>();
    defaultHeaders.add(new BasicHeader(HttpHeaders.PRAGMA, "no-cache"));
    defaultHeaders.add(new BasicHeader(HttpHeaders.CACHE_CONTROL, "no-cache"));

    final HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(defaultHeaders).disableAuthCaching().disableContentCompression();
    this.httpClient = httpClientBuilder.setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
}
项目:Cognizant-Intelligent-Test-Scripter    文件:AbstractHttpClient.java   
/**
 * custom http client for server with SSL errors
 *
 * @return
 */
public final CloseableHttpClient getCustomClient() {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
        builder.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        builder.setConnectionManager(connMgr);
        return builder.build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return getSystemClient();
}
项目:aws-sdk-java-v2    文件:ApacheConnectionManagerFactory.java   
public HttpClientConnectionManager create(ApacheSdkHttpClientFactory configuration,
                                          AttributeMap standardOptions) {
    ConnectionSocketFactory sslsf = getPreferredSocketFactory(standardOptions);

    final PoolingHttpClientConnectionManager cm = new
            PoolingHttpClientConnectionManager(
            createSocketFactoryRegistry(sslsf),
            null,
            DefaultSchemePortResolver.INSTANCE,
            null,
            configuration.connectionTimeToLive().orElse(Defaults.CONNECTION_POOL_TTL).toMillis(),
            TimeUnit.MILLISECONDS);

    cm.setDefaultMaxPerRoute(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
    cm.setMaxTotal(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
    cm.setDefaultSocketConfig(buildSocketConfig(standardOptions));

    return cm;
}
项目:seldon-core    文件:InternalPredictionService.java   
@Autowired
public InternalPredictionService(AppProperties appProperties){
    this.appProperties = appProperties;
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(150);
    connectionManager.setDefaultMaxPerRoute(150);

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(DEFAULT_REQ_TIMEOUT)
            .setConnectTimeout(DEFAULT_CON_TIMEOUT)
            .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();

    httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new HttpRetryHandler())
            .build();
}
项目:ibm-cos-sdk-java    文件:ApacheConnectionManagerFactory.java   
@Override
public HttpClientConnectionManager create(final HttpClientSettings settings) {
    ConnectionSocketFactory sslsf = getPreferredSocketFactory(settings);

    final PoolingHttpClientConnectionManager cm = new
            PoolingHttpClientConnectionManager(
            createSocketFactoryRegistry(sslsf),
            null,
            DefaultSchemePortResolver.INSTANCE,
            new DelegatingDnsResolver(settings.getDnsResolver()),
            settings.getConnectionPoolTTL(),
            TimeUnit.MILLISECONDS);

    cm.setValidateAfterInactivity(settings.getValidateAfterInactivityMillis());
    cm.setDefaultMaxPerRoute(settings.getMaxConnections());
    cm.setMaxTotal(settings.getMaxConnections());
    cm.setDefaultSocketConfig(buildSocketConfig(settings));
    cm.setDefaultConnectionConfig(buildConnectionConfig(settings));

    return cm;
}
项目:rest-client    文件:RestClient.java   
RestClient(String baseUrl,
           ObjectMapper objectMapper,
           Map<String, Object> defaultHeaders,
           Function<String, String> urlTransformer,
           PoolingNHttpClientConnectionManager asyncConnectionManager,
           PoolingHttpClientConnectionManager syncConnectionManager,
           CloseableHttpAsyncClient asyncClient,
           CloseableHttpClient syncClient) {
    this.objectMapper = objectMapper;
    this.baseUrl = baseUrl;
    this.urlTransformer = urlTransformer;
    this.asyncConnectionManager = asyncConnectionManager;
    this.syncConnectionManager = syncConnectionManager;
    this.asyncClient = asyncClient;
    this.syncClient = syncClient;
    this.defaultHeaders.putAll(defaultHeaders);
    this.id = UUID.randomUUID().toString().substring(0, 8);
}
项目:vk-java-sdk    文件:HttpTransportClient.java   
public HttpTransportClient(int retryAttemptsNetworkErrorCount, int retryAttemptsInvalidStatusCount) {
    this.retryAttemptsNetworkErrorCount = retryAttemptsNetworkErrorCount;
    this.retryAttemptsInvalidStatusCount = retryAttemptsInvalidStatusCount;

    CookieStore cookieStore = new BasicCookieStore();
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(SOCKET_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS)
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS);

    httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .setDefaultCookieStore(cookieStore)
            .setUserAgent(USER_AGENT)
            .build();
}
项目:metacat    文件:DruidHttpClientConfig.java   
/**
 * Http client.
 *
 * @param connectorContext connector context
 * @return HttpClient
 */
@Bean
public HttpClient httpClient(final ConnectorContext connectorContext) {
    final int timeout = (int) TimeUtil.toTime(
        connectorContext.getConfiguration().getOrDefault(DruidConfigConstants.HTTP_TIMEOUT, "5s"),
        TimeUnit.SECONDS,
        TimeUnit.MILLISECONDS
    );
    final int poolsize = Integer.parseInt(connectorContext.getConfiguration()
        .getOrDefault(DruidConfigConstants.POOL_SIZE, "10"));
    final RequestConfig config = RequestConfig.custom()
        .setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setSocketTimeout(timeout)
        .setMaxRedirects(3)
        .build();
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(poolsize);
    return HttpClientBuilder
        .create()
        .setDefaultRequestConfig(config)
        .setConnectionManager(connectionManager)
        .build();
}
项目:cathode    文件:Dispatcher.java   
Dispatcher(final String clientID, final String authToken) {
    undocumented = new UndocumentedDispatcher();

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(CONNECTION_COUNT);
    connectionManager.setDefaultMaxPerRoute(CONNECTION_COUNT);

    final List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader(HttpHeaders.ACCEPT, "application/vnd.twitchtv.v3+json"));
    headers.add(new BasicHeader("Client-ID", clientID));
    if (authToken != null) {
        headers.add(new BasicHeader("Authorization", "OAuth " + authToken));
    }

    HTTP_CLIENT = HttpClients.custom().setDefaultHeaders(headers).setConnectionManager(connectionManager).build();
}
项目:dmaap-framework    文件:SAClient.java   
public SAClient(Collection<HttpHost> hosts) {
    this.loadBalancingPolicy = new StickyLoadBalancingPolicy<URI, HttpHost> (hosts);

    final PoolingHttpClientConnectionManager fClientCm = new PoolingHttpClientConnectionManager();
    fClientCm.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    fClientCm.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);

    this.fClient = createDefaultClient(fClientCm);

    this.fConnectionSweeper = Executors.newSingleThreadScheduledExecutor();
    this.fConnectionSweeper.scheduleAtFixedRate(
            new SAConnectionMonitorThread(fClientCm, DEFAULT_CONN_TIMEOUT_IN_SECS, TimeUnit.SECONDS),
            DEFAULT_SWEEP_PERIOD_IN_SECS,
            DEFAULT_SWEEP_PERIOD_IN_SECS,
            TimeUnit.SECONDS
    );
}
项目:dmaap-framework    文件:SAClient.java   
public SAClient(LoadBalancingPolicy<URI, HttpHost> loadBalancingPolicy) {
    this.loadBalancingPolicy = loadBalancingPolicy;

    final PoolingHttpClientConnectionManager fClientCm = new PoolingHttpClientConnectionManager();
    fClientCm.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    fClientCm.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);

    this.fClient = createDefaultClient(fClientCm);

    this.fConnectionSweeper = Executors.newSingleThreadScheduledExecutor();
    this.fConnectionSweeper.scheduleAtFixedRate(
            new SAConnectionMonitorThread(fClientCm, DEFAULT_CONN_TIMEOUT_IN_SECS, TimeUnit.SECONDS),
            DEFAULT_SWEEP_PERIOD_IN_SECS,
            DEFAULT_SWEEP_PERIOD_IN_SECS,
            TimeUnit.SECONDS
    );
}
项目:rapid    文件:DockerClient.java   
private void init() {
    final URI originalUri = URI.create(DEFAULT_UNIX_ENDPOINT);
    sanitizeUri = UnixFactory.sanitizeUri(originalUri);

    final RegistryBuilder<ConnectionSocketFactory> registryBuilder =
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", SSLConnectionSocketFactory.getSocketFactory())
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("unix", new UnixFactory(originalUri));

    final PoolingHttpClientConnectionManager cm =
            new PoolingHttpClientConnectionManager(registryBuilder.build());

    final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout((int) SECONDS.toMillis(5))
            .setConnectTimeout((int) SECONDS.toMillis(5))
            .setSocketTimeout((int) SECONDS.toMillis(30))
            .build();

    final ClientConfig config = new ClientConfig()
            .connectorProvider(new ApacheConnectorProvider())
            .property(ApacheClientProperties.CONNECTION_MANAGER, cm)
            .property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);

    client = ClientBuilder.newBuilder().withConfig(config).build();
}
项目:cosmic    文件:HttpClientHelper.java   
public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    s_logger.info("Creating new HTTP connection pool and client");
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration();
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connManager.setDefaultMaxPerRoute(MAX_ALLOCATED_CONNECTIONS_PER_ROUTE);
    connManager.setMaxTotal(MAX_ALLOCATED_CONNECTIONS);
    final RequestConfig requestConfig = RequestConfig.custom()
                                                     .setCookieSpec(CookieSpecs.DEFAULT)
                                                     .setMaxRedirects(maxRedirects)
                                                     .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                                                     .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
                                                     .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
                                                     .build();
    return HttpClientBuilder.create()
                            .setConnectionManager(connManager)
                            .setRedirectStrategy(new LaxRedirectStrategy())
                            .setDefaultRequestConfig(requestConfig)
                            .setDefaultCookieStore(cookieStore)
                            .setRetryHandler(new StandardHttpRequestRetryHandler())
                            .build();
}
项目:cos-java-sdk-v4    文件:AbstractCosHttpClient.java   
public AbstractCosHttpClient(ClientConfig config) {
    super();
    this.config = config;
    this.connectionManager = new PoolingHttpClientConnectionManager();
    this.connectionManager.setMaxTotal(config.getMaxConnectionsCount());
    this.connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsCount());
    this.connectionManager.setValidateAfterInactivity(1);
    HttpClientBuilder httpClientBuilder =
            HttpClients.custom().setConnectionManager(connectionManager);
    if (config.getHttpProxyIp() != null && config.getHttpProxyPort() != 0) {
        HttpHost proxy = new HttpHost(config.getHttpProxyIp(), config.getHttpProxyPort());
        httpClientBuilder.setProxy(proxy);
    }
    this.httpClient = httpClientBuilder.build();
    this.requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(this.config.getConnectionRequestTimeout())
            .setConnectTimeout(this.config.getConnectionTimeout())
            .setSocketTimeout(this.config.getSocketTimeout()).build();
    this.idleConnectionMonitor = new IdleConnectionMonitorThread(this.connectionManager);
    this.idleConnectionMonitor.setDaemon(true);
    this.idleConnectionMonitor.start();
}
项目:java-triton    文件:CloudApiConnectionFactory.java   
/**
 * Creates a new configured instance of {@link CloseableHttpClient} based
 * on the factory's configuration.
 *
 * @return new connection object instance
 */
public CloseableHttpClient createConnection() {
    final ConnectionSocketFactory socketFactory =
            new CloudApiSSLConnectionSocketFactory(config);

    final RegistryBuilder<ConnectionSocketFactory> registryBuilder =
            RegistryBuilder.create();

    final Registry<ConnectionSocketFactory> socketFactoryRegistry = registryBuilder
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", socketFactory)
            .build();

    final PoolingHttpClientConnectionManager connectionManager =
            new PoolingHttpClientConnectionManager(socketFactoryRegistry,
                    DNS_RESOLVER);

    httpClientBuilder.setConnectionManager(connectionManager);

    return httpClientBuilder.build();
}
项目:ibm-bpm-rest-client    文件:SimpleBpmClient.java   
private CloseableHttpClient createClient(String user, String password) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(TOTAL_CONN);
    cm.setDefaultMaxPerRoute(ROUTE_CONN);

    logger.info("Pooling connection manager created.");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    logger.info("Default credentials provider created.");

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();

    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicAuth);
    logger.info("Auth cache created.");

    httpContext = HttpClientContext.create();
    httpContext.setCredentialsProvider(credentialsProvider);
    httpContext.setAuthCache(authCache);
    logger.info("HttpContext filled with Auth cache.");

    return HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm)
            .build();
}
项目:dtsopensource    文件:HttpProtocolParent.java   
private CloseableHttpClient createHttpClient(String hostname, int port) {
    ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", plainsf).register("https", sslsf).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    // 将最大连接数增加
    cm.setMaxTotal(maxTotal);
    // 将每个路由基础的连接增加
    cm.setDefaultMaxPerRoute(maxPerRoute);
    HttpHost httpHost = new HttpHost(hostname, port);
    // 将目标主机的最大连接数增加
    cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
    // 请求重试处理
    return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
项目:aet    文件:ExternalSnippetHttpClient.java   
@Activate
protected void activate(Map<String, Object> properties) {
  LOGGER.info("Activating ExternalSnippetHttpClient - {}", this);

  Long connectionTtl = PropertiesUtil
      .toLong(properties.get(CONNECTION_TTL_PARAMETER), DEFAULT_CONNECTION_TTL);
  Integer maxConcurrentConnections = PropertiesUtil
      .toInteger(properties.get(MAX_CONCURRENT_CONNECTIONS_PARAMETER),
          DEFAULT_MAX_CONCURRENT_CONNECTIONS);

  final PoolingHttpClientConnectionManager poolingConnManager =
      new PoolingHttpClientConnectionManager(connectionTtl, TimeUnit.SECONDS);
  poolingConnManager.setMaxTotal(maxConcurrentConnections);

  httpClient = HttpClients.custom().setConnectionManager(poolingConnManager).build();
}
项目:flux    文件:FluxRuntimeConnectorHttpImpl.java   
public FluxRuntimeConnectorHttpImpl(Long connectionTimeout, Long socketTimeout, String fluxEndpoint, ObjectMapper objectMapper) {
    this.fluxEndpoint = fluxEndpoint;
    this.objectMapper = objectMapper;
    RequestConfig clientConfig = RequestConfig.custom()
        .setConnectTimeout((connectionTimeout).intValue())
        .setSocketTimeout((socketTimeout).intValue())
        .setConnectionRequestTimeout((socketTimeout).intValue())
        .build();
    PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager();
    syncConnectionManager.setMaxTotal(MAX_TOTAL);
    syncConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);

    closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager)
        .build();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        HttpClientUtils.closeQuietly(closeableHttpClient);
    }));
}
项目:Camel    文件:HttpComponent.java   
protected HttpClientConnectionManager createConnectionManager(Registry<ConnectionSocketFactory> registry, int maxTotalConnections, int connectionsPerRoute) {
    // setup the connection live time
    PoolingHttpClientConnectionManager answer = 
        new PoolingHttpClientConnectionManager(registry, null, null, null, getConnectionTimeToLive(), TimeUnit.MILLISECONDS);
    int localMaxTotalConnections = maxTotalConnections;
    if (localMaxTotalConnections == 0) {
        localMaxTotalConnections = getMaxTotalConnections();
    }
    if (localMaxTotalConnections > 0) {
        answer.setMaxTotal(localMaxTotalConnections);
    }
    int localConnectionsPerRoute = connectionsPerRoute;
    if (localConnectionsPerRoute == 0) {
        localConnectionsPerRoute = getConnectionsPerRoute();
    }
    if (localConnectionsPerRoute > 0) {
        answer.setDefaultMaxPerRoute(localConnectionsPerRoute);
    }
    LOG.info("Created ClientConnectionManager " + answer);

    return answer;
}
项目:purecloud-iot    文件:LocalServerTestBase.java   
@Before
public void setUp() throws Exception {
    final SocketConfig socketConfig = SocketConfig.custom()
            .setSoTimeout(15000)
            .build();
    this.serverBootstrap = ServerBootstrap.bootstrap()
            .setSocketConfig(socketConfig)
            .setServerInfo(ORIGIN)
            .registerHandler("/echo/*", new EchoHandler())
            .registerHandler("/random/*", new RandomHandler());
    if (this.scheme.equals(ProtocolScheme.https)) {
        this.serverBootstrap.setSslContext(SSLTestContexts.createServerSSLContext());
    }

    this.connManager = new PoolingHttpClientConnectionManager();
    this.clientBuilder = HttpClientBuilder.create()
            .setDefaultSocketConfig(socketConfig)
            .setConnectionManager(this.connManager);
}
项目:FHIR-Server    文件:PreferTest.java   
@BeforeClass
public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    PatientProvider patientProvider = new PatientProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer();
    servlet.setResourceProviders(patientProvider);
    ServletHolder servletHolder = new ServletHolder(servlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();

}
项目:carbon-device-mgt    文件:RESTInvoker.java   
private void configureHttpClient() {
    int connectionTimeout = 120000;
    int socketTimeout = 120000;
    int maxTotalConnectionsPerRoute = 100;
    int maxTotalConnections = 100;
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout)
            .setSocketTimeout(socketTimeout)
            .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute);
    connectionManager.setMaxTotal(maxTotalConnections);
    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();
    if (log.isDebugEnabled()) {
        log.debug("REST client initialized with " +
                "maxTotalConnection = " + maxTotalConnections +
                "maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute +
                "connectionTimeout = " + connectionTimeout);
    }

}
项目:ha-bridge    文件:HttpClientPool.java   
private Singleton() {
  PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
  // Increase max total connection to 200
  cm.setMaxTotal(200);
  // Increase default max connection per route to 20
  cm.setDefaultMaxPerRoute(20);
  // Build the client.
  threadSafeClient = HttpClients.custom()
          .setConnectionManager(cm)
          .build();
  // Start up an eviction thread.
  monitor = new IdleConnectionMonitorThread(cm);
  // Don't stop quitting.
  monitor.setDaemon(true);
  monitor.start();
}
项目:FHIR-Server    文件:DeleteConditionalTest.java   
@BeforeClass
public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    PatientProvider patientProvider = new PatientProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer();
    servlet.setResourceProviders(patientProvider);
    ServletHolder servletHolder = new ServletHolder(servlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();

}
项目:FHIR-Server    文件:SearchDstu2Test.java   
@BeforeClass
public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer();

    servlet.setResourceProviders(patientProvider);
    ServletHolder servletHolder = new ServletHolder(servlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();

}
项目:ranger    文件:PingCheckMonitor.java   
/**
 * @param timeEntity                how often the {@link #monitor()} check needs to be executed
 * @param httpRequest               http request that will be called at regular intervals
 * @param pingTimeoutInMilliseconds timeout in milliseconds for http request execution (ping response)
 * @param pingWindowSize            rolling window frame, which needs to be maintained
 * @param maxFailures               maximum failures allowed in the rolling window frame
 * @param host                      host name (could be localhost)
 * @param port                      port
 */
public PingCheckMonitor(TimeEntity timeEntity,
                        HttpRequest httpRequest,
                        Integer pingTimeoutInMilliseconds,
                        Integer pingWindowSize,
                        Integer maxFailures,
                        String host,
                        Integer port) {
    super(PingCheckMonitor.class.getSimpleName(), timeEntity);
    this.httpRequest = httpRequest;
    this.pingTimeoutInMilliseconds = pingTimeoutInMilliseconds;
    this.host = host;
    this.port = port;
    this.rollingWindowHealthQueue = new RollingWindowHealthQueue(pingWindowSize, maxFailures);
    this.executorService = Executors.newSingleThreadExecutor();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(host, port)), 2);
    this.httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();
}
项目:FHIR-Server    文件:ReadTest.java   
@BeforeClass
public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    PatientProvider patientProvider = new PatientProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer();
    ourCtx = servlet.getFhirContext();
    servlet.setResourceProviders(patientProvider, new BinaryProvider(), new OrganizationProviderWithAbstractReturnType());
    ServletHolder servletHolder = new ServletHolder(servlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();

}
项目:FHIR-Server    文件:BinaryTest.java   
@BeforeClass
public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    ResourceProvider patientProvider = new ResourceProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer();
    servlet.setResourceProviders(patientProvider);
    ServletHolder servletHolder = new ServletHolder(servlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();

}
项目:dasein-cloud-azurepack    文件:AzurePackCloud.java   
public HttpClientBuilder getAzureClientBuilder() throws CloudException {
    try {

        //boolean disableSSLValidation = isSSLValidationDisabled();
        boolean disableSSLValidation = true;
        HttpClientBuilder builder = HttpClientBuilder.create();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", new AzureSSLSocketFactory(new AzureX509(this), disableSSLValidation))
                .build();

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(20);
        builder.setConnectionManager(connManager);
        return builder;
    } catch (Exception e) {
        throw new CloudException(e.getMessage());
    }
}
项目:FHIR-Server    文件:UpdateConditionalTest.java   
@BeforeClass
public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    PatientProvider patientProvider = new PatientProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer();
    servlet.setResourceProviders(patientProvider);
    ServletHolder servletHolder = new ServletHolder(servlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();

}
项目:antioch    文件:AntiochClient.java   
public AntiochClient(final URI antiochURI, SSLContext sslContext) {
  this.antiochURI = antiochURI;
  final ObjectMapper objectMapper = new ObjectMapper()//
      .registerModule(new Jdk8Module())//
      .registerModule(new JavaTimeModule());

  final JacksonJaxbJsonProvider jacksonProvider = new JacksonJaxbJsonProvider();
  jacksonProvider.setMapper(objectMapper);

  PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
  cm.setMaxTotal(50);
  cm.setDefaultMaxPerRoute(50);

  ApacheConnectorProvider connectorProvider = new ApacheConnectorProvider();
  ClientConfig clientConfig = new ClientConfig(jacksonProvider)//
      .connectorProvider(connectorProvider)//
      .property(ApacheClientProperties.CONNECTION_MANAGER, cm)//
      .property(ClientProperties.CONNECT_TIMEOUT, 60000)//
      .property(ClientProperties.READ_TIMEOUT, 60000);

  if (sslContext == null) {
    if ("https".equals(antiochURI.getScheme())) {
      throw new RuntimeException("SSL connections need an SSLContext, use: new AntiochClient(uri, sslContext) instead.");
    }
    client = ClientBuilder.newClient(clientConfig);

  } else {
    client = ClientBuilder.newBuilder()//
        .sslContext(sslContext)//
        .withConfig(clientConfig)//
        .build();
  }
  rootTarget = client.target(antiochURI);
}