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; }
/** * Returns a wrapped instance of {@link HttpClientConnectionManager} * to capture the necessary performance metrics. * * @param orig the target instance to be wrapped */ public static HttpClientConnectionManager wrap(HttpClientConnectionManager orig) { if (orig instanceof Wrapped) { throw new IllegalArgumentException(); } final Class<?>[] interfaces; if (orig instanceof ConnPoolControl) { interfaces = new Class<?>[]{ HttpClientConnectionManager.class, ConnPoolControl.class, Wrapped.class}; } else { interfaces = new Class<?>[]{ HttpClientConnectionManager.class, Wrapped.class }; } return (HttpClientConnectionManager) Proxy.newProxyInstance( // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423 ClientConnectionManagerFactory.class.getClassLoader(), interfaces, new Handler(orig)); }
@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; }
/** * Returns a wrapped instance of {@link HttpClientConnectionManager} * to capture the necessary performance metrics. * * @param orig the target instance to be wrapped */ public static HttpClientConnectionManager wrap (HttpClientConnectionManager orig) { if (orig instanceof Wrapped) throw new IllegalArgumentException(); final Class<?>[] interfaces; if (orig instanceof ConnPoolControl) { interfaces = new Class<?>[]{ HttpClientConnectionManager.class, ConnPoolControl.class, Wrapped.class }; } else { interfaces = new Class<?>[]{ HttpClientConnectionManager.class, Wrapped.class }; } return (HttpClientConnectionManager) Proxy.newProxyInstance( // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423 ClientConnectionManagerFactory.class.getClassLoader(), interfaces, new Handler(orig)); }
@Test public void autoShutdown() throws Exception { assertEquals(0, IdleConnectionReaper.size()); for (int i = 0; i < 3; i++) { HttpClientConnectionManager m = new TestClientConnectionManager(); HttpClientConnectionManager m2 = new TestClientConnectionManager(); assertTrue(IdleConnectionReaper.registerConnectionManager(m)); assertEquals(1, IdleConnectionReaper.size()); assertTrue(IdleConnectionReaper.registerConnectionManager(m2)); assertEquals(2, IdleConnectionReaper.size()); assertTrue(IdleConnectionReaper.removeConnectionManager(m)); assertEquals(1, IdleConnectionReaper.size()); assertTrue(IdleConnectionReaper.removeConnectionManager(m2)); assertEquals(0, IdleConnectionReaper.size()); assertFalse(IdleConnectionReaper.shutdown()); } }
public static CloseableHttpClient getHttpClient(HttpClientConnectionManager connectionManager, int maxConnections) { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build(); SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true) .setSoReuseAddress(true).build(); String userAgent = MessageFormat .format("MyCoRe/{0} ({1}; java {2})", MCRCoreVersion.getCompleteVersion(), MCRConfiguration.instance() .getString("MCR.NameOfProject", "undefined"), System.getProperty("java.version")); //setup http client return HttpClients.custom().setConnectionManager(connectionManager) .setUserAgent(userAgent).setRetryHandler(new MCRRetryHandler(maxConnections)) .setDefaultRequestConfig(requestConfig).setDefaultConnectionConfig(connectionConfig) .setDefaultSocketConfig(socketConfig).build(); }
private CloseableHttpClient createDefaultClient(HttpClientConnectionManager fClientCm) { final CacheConfig cacheConfig = CacheConfig.custom() .setMaxCacheEntries(DEFAULT_CACHE_MAX_ENTRIES) .setMaxObjectSize(DEFAULT_CACHE_MAX_OBJ_SIZE) .setHeuristicCachingEnabled(true) .setHeuristicDefaultLifetime(DEFAULT_CACHE_TTL_IN_SECS) .build(); final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(DEFAULT_REQUEST_CONN_TIMEOUT_IN_MS) .setSocketTimeout(DEFAULT_REQUEST_SOCK_TIMEOUT_IN_MS) .build(); return CachingHttpClients.custom() .setCacheConfig(cacheConfig) .setConnectionManager(fClientCm) .setDefaultRequestConfig(requestConfig) .build(); }
public MinimalClientExec( final HttpRequestExecutor requestExecutor, final HttpClientConnectionManager connManager, final ConnectionReuseStrategy reuseStrategy, final ConnectionKeepAliveStrategy keepAliveStrategy) { Args.notNull(requestExecutor, "HTTP request executor"); Args.notNull(connManager, "Client connection manager"); Args.notNull(reuseStrategy, "Connection reuse strategy"); Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); this.httpProcessor = new ImmutableHttpProcessor( new RequestContentHC4(), new RequestTargetHostHC4(), new RequestClientConnControl(), new RequestUserAgentHC4(VersionInfoHC4.getUserAgent( "Apache-HttpClient", "org.apache.http.client", getClass()))); this.requestExecutor = requestExecutor; this.connManager = connManager; this.reuseStrategy = reuseStrategy; this.keepAliveStrategy = keepAliveStrategy; }
public InternalHttpClient( final ClientExecChain execChain, final HttpClientConnectionManager connManager, final HttpRoutePlanner routePlanner, final Lookup<CookieSpecProvider> cookieSpecRegistry, final Lookup<AuthSchemeProvider> authSchemeRegistry, final CookieStore cookieStore, final CredentialsProvider credentialsProvider, final RequestConfig defaultConfig, final List<Closeable> closeables) { super(); Args.notNull(execChain, "HTTP client exec chain"); Args.notNull(connManager, "HTTP connection manager"); Args.notNull(routePlanner, "HTTP route planner"); this.execChain = execChain; this.connManager = connManager; this.routePlanner = routePlanner; this.cookieSpecRegistry = cookieSpecRegistry; this.authSchemeRegistry = authSchemeRegistry; this.cookieStore = cookieStore; this.credentialsProvider = credentialsProvider; this.defaultConfig = defaultConfig; this.closeables = closeables; }
public void performLogoutOnServiceProviders(String idpSessionId) { List<String> serviceProviderLogoutUrls = idpConfig.getServiceProviderLogoutUrls(); asyncServiceLogoutExecutor.submit(() -> { HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(); HttpClient client = HttpClientBuilder.create() .setConnectionManager(connectionManager) .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) .build(); try { for (String serviceProviderLogoutUrl : serviceProviderLogoutUrls) { callLoggedOutServiceUrl(client, serviceProviderLogoutUrl, idpSessionId); } } catch (Throwable ex) { log.error("Unable to perform logout on IDP services for session {}", idpSessionId, ex); } finally { connectionManager.shutdown(); } }); }
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; }
public MinimalClientExec( final HttpRequestExecutor requestExecutor, final HttpClientConnectionManager connManager, final ConnectionReuseStrategy reuseStrategy, final ConnectionKeepAliveStrategy keepAliveStrategy) { Args.notNull(requestExecutor, "HTTP request executor"); Args.notNull(connManager, "Client connection manager"); Args.notNull(reuseStrategy, "Connection reuse strategy"); Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); this.httpProcessor = new ImmutableHttpProcessor( new RequestContent(), new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent(VersionInfo.getUserAgent( "Apache-HttpClient", "org.apache.http.client", getClass()))); this.requestExecutor = requestExecutor; this.connManager = connManager; this.reuseStrategy = reuseStrategy; this.keepAliveStrategy = keepAliveStrategy; }
/** * Produces an instance of {@link ClientExecChain} to be used as a main exec. * <p> * Default implementation produces an instance of {@link MainClientExec} * </p> * <p> * For internal use. * </p> * * @since 4.4 */ protected ClientExecChain createMainExec( final HttpRequestExecutor requestExec, final HttpClientConnectionManager connManager, final ConnectionReuseStrategy reuseStrategy, final ConnectionKeepAliveStrategy keepAliveStrategy, final HttpProcessor proxyHttpProcessor, final AuthenticationStrategy targetAuthStrategy, final AuthenticationStrategy proxyAuthStrategy, final UserTokenHandler userTokenHandler) { return new MainClientExec( requestExec, connManager, reuseStrategy, keepAliveStrategy, proxyHttpProcessor, targetAuthStrategy, proxyAuthStrategy, userTokenHandler); }
@Test public void testEvictExpiredAndIdle() throws Exception { final HttpClientConnectionManager cm = Mockito.mock(HttpClientConnectionManager.class); final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm, 500, TimeUnit.MILLISECONDS, 3, TimeUnit.SECONDS); connectionEvictor.start(); Thread.sleep(1000); Mockito.verify(cm, Mockito.atLeast(1)).closeExpiredConnections(); Mockito.verify(cm, Mockito.atLeast(1)).closeIdleConnections(3000, TimeUnit.MILLISECONDS); Assert.assertTrue(connectionEvictor.isRunning()); connectionEvictor.shutdown(); connectionEvictor.awaitTermination(1, TimeUnit.SECONDS); Assert.assertFalse(connectionEvictor.isRunning()); }
@Test public void testEvictExpiredOnly() throws Exception { final HttpClientConnectionManager cm = Mockito.mock(HttpClientConnectionManager.class); final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm, 500, TimeUnit.MILLISECONDS, 0, TimeUnit.SECONDS); connectionEvictor.start(); Thread.sleep(1000); Mockito.verify(cm, Mockito.atLeast(1)).closeExpiredConnections(); Mockito.verify(cm, Mockito.never()).closeIdleConnections(Mockito.anyLong(), Mockito.<TimeUnit>any()); Assert.assertTrue(connectionEvictor.isRunning()); connectionEvictor.shutdown(); connectionEvictor.awaitTermination(1, TimeUnit.SECONDS); Assert.assertFalse(connectionEvictor.isRunning()); }
@SuppressWarnings("unchecked") @Before public void setup() throws Exception { execChain = Mockito.mock(ClientExecChain.class); connManager = Mockito.mock(HttpClientConnectionManager.class); routePlanner = Mockito.mock(HttpRoutePlanner.class); cookieSpecRegistry = Mockito.mock(Lookup.class); authSchemeRegistry = Mockito.mock(Lookup.class); cookieStore = Mockito.mock(CookieStore.class); credentialsProvider = Mockito.mock(CredentialsProvider.class); defaultConfig = RequestConfig.custom().build(); closeable1 = Mockito.mock(Closeable.class); closeable2 = Mockito.mock(Closeable.class); client = new InternalHttpClient(execChain, connManager, routePlanner, cookieSpecRegistry, authSchemeRegistry, cookieStore, credentialsProvider, defaultConfig, Arrays.asList(closeable1, closeable2)); }
/** * Verify that eviction thread will continue to run even if calls on ClientConnectionManager fails. * * @throws Exception unexpected */ @Test public void evictionContinuesWhenConnectionManagerFails() throws Exception { final HttpClientConnectionManager clientConnectionManager = mock(HttpClientConnectionManager.class); doThrow(new RuntimeException("closeExpiredConnections")).when(clientConnectionManager) .closeExpiredConnections(); doThrow(new RuntimeException("closeIdleConnections")).when(clientConnectionManager) .closeIdleConnections(1000, TimeUnit.MILLISECONDS); final ConnectionEvictionThread underTest = new ConnectionEvictionThread(clientConnectionManager, 1000, 100); underTest.start(); Thread.sleep(300); verify(clientConnectionManager, atLeast(2)).closeExpiredConnections(); verify(clientConnectionManager, atLeast(2)).closeIdleConnections(1000, TimeUnit.MILLISECONDS); underTest.interrupt(); }
/** * Customizes the configuration of the httpClientBuilder. * * <p>Internally, this uses several helper methods to assist with configuring: * <ul> * <li>Calls {@link #buildConnectionManager()} and sets the resulting {@link HttpClientConnectionManager} (if * non-null) into the httpClientBuilder.</li> * <li>Calls {@link #buildRequestConfig()} and sets the resulting {@link RequestConfig} (if non-null) into the * httpClientBuilder.</li> * <li>Calls {@link #buildRetryHandler()} and sets the resulting {@link HttpRequestRetryHandler} (if non-null) * into the httpClientBuilder.</li> * </ul> * </p> * * @param httpClientBuilder the httpClientBuilder being configured */ @Override public void customizeHttpClient(HttpClientBuilder httpClientBuilder) { HttpClientConnectionManager connectionManager = buildConnectionManager(); if (connectionManager != null) { httpClientBuilder.setConnectionManager(connectionManager); } RequestConfig requestConfig = buildRequestConfig(); if (requestConfig != null) { httpClientBuilder.setDefaultRequestConfig(requestConfig); } HttpRequestRetryHandler retryHandler = buildRetryHandler(); if (retryHandler != null) { httpClientBuilder.setRetryHandler(retryHandler); } }
/** * This code sets up the httpclient to accept any SSL certificate. The * SSL certificate generated by the instructions above is not correctly * signed, so we need ignore the problem. * This code should not, under any circumstances, be allowed anywhere * the production code. * @return */ private CloseableHttpClient createClient () { try { HttpClientBuilder builder = HttpClientBuilder.create(); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[]{getTrustManager()}, null); SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(scsf); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", scsf) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); return builder.build(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
protected HttpClientConnectionManager createConnectionManager() { if (httpClientConfig.isMultiThreaded()) { log.debug("Multi-threaded http connection manager created"); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); final Integer maxTotal = httpClientConfig.getMaxTotalConnection(); if (maxTotal != null) { cm.setMaxTotal(maxTotal); } final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute(); if (defaultMaxPerRoute != null) { cm.setDefaultMaxPerRoute(defaultMaxPerRoute); } final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute(); for (final HttpRoute route : maxPerRoute.keySet()) { cm.setMaxPerRoute(route, maxPerRoute.get(route)); } return cm; } log.debug("Default http connection is created without multi threaded option"); return new BasicHttpClientConnectionManager(); }
@Bean @ConditionalOnMissingBean(HttpClient.class) public HttpClient httpClient(){ HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(30000) .setConnectTimeout(30000) .setTargetPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)) .setProxyPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)) .build(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, getUsernamePasswordCredentials()); return HttpClients.custom().setConnectionManager(cm) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(requestConfig) .build(); }
@Override protected void configure() { bind(HttpClientConnectionManager.class) .toInstance(new PoolingHttpClientConnectionManager()); bind(ScheduledExecutorService.class) .toInstance(Executors.newSingleThreadScheduledExecutor()); bind(CalendarServiceData.class) .toProvider(CalendarServiceDataProvider.class) .in(Scopes.SINGLETON); bind(GtfsRelationalDao.class) .toProvider(GtfsRelationalDaoProvider.class) .in(Scopes.SINGLETON); bind(TimeZone.class) .annotatedWith(AgencyTimeZone.class) .toProvider(AgencyTimeZoneProvider.class) .in(Scopes.SINGLETON); }
private static CloseableHttpClient createInsecureSslHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { final SSLContext sslContext = new SSLContextBuilder() .useProtocol(INSECURE_SSL_PROTOCOL) .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf) .build(); final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry); return HttpClients.custom() .setConnectionManager(connectionManager) .setSSLSocketFactory( sslsf).build(); }
public static void main(String[] args) { // Injection Code final HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(); final ExecutorFactory executorFactory = new HC435ExecutorFactory(httpClientConnectionManager); final OAuth2Client client = prepareOAuth2Client(); final OAuth2Token token = prepareOAuth2Token(); // ResTZ Example Code final Executor executor = executorFactory.get(); final ResTZ restz = new ResTZ(executor); final BoxApi boxApi = new BoxApi(restz, client, token); final BoxFolder boxFolder = boxApi.createFolder("top-level-folder", "0"); final BoxFile boxFile = boxApi.uploadFile(boxFolder.getId(), new File("/test/test.zip")); downloadFile(boxApi, boxFile.getId(), "/test/test-downloaded.zip"); }
public static void main(String[] args) { // Injection Code final HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(); final ExecutorFactory executorFactory = new HC435ExecutorFactory(httpClientConnectionManager); final InstanceProperties instanceProperties = prepareInstanceProperties(); final OfficeOAuth2Client client = prepareOAuth2Client(); final OfficeOAuth2Token token = prepareOAuth2Token(); // ResTZ Example Code final Executor executor = executorFactory.get(); final ResTZ restz = new ResTZ(executor); final OfficeApi officeApi = new OfficeApi(instanceProperties, restz, client, token); final SiteCreationResponse site = officeApi.createSite("my-site"); final String siteRelativeUrl = site.getServerRelativeUrl(); final FolderCreationResponse folder = officeApi.createFolder(siteRelativeUrl, "my-folder"); final String folderId = folder.getUniqueId(); uploadAndDownloadFile(officeApi, siteRelativeUrl, folderId, "/test/test.zip", "/test/test-downloaded.zip"); }
@Bean @ConditionalOnMissingBean(HttpClientConnectionManager.class) public HttpClientConnectionManager httpClientConnectionManager( IClientConfig config, ApacheHttpClientConnectionManagerFactory connectionManagerFactory) { RibbonProperties ribbon = RibbonProperties.from(config); int maxTotalConnections = ribbon.maxTotalConnections(); int maxConnectionsPerHost = ribbon.maxConnectionsPerHost(); int timerRepeat = ribbon.connectionCleanerRepeatInterval(); long timeToLive = ribbon.poolKeepAliveTime(); TimeUnit ttlUnit = ribbon.getPoolKeepAliveTimeUnits(); final HttpClientConnectionManager connectionManager = connectionManagerFactory .newConnectionManager(false, maxTotalConnections, maxConnectionsPerHost, timeToLive, ttlUnit, registryBuilder); this.connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { connectionManager.closeExpiredConnections(); } }, 30000, timerRepeat); return connectionManager; }
/** * Create connection manager for http client. * * @return The connection manager for http client. */ private HttpClientConnectionManager createHttpClientConnectionManager() { ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslSocketFactory; try { sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(), SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException e) { throw new BceClientException("Fail to create SSLConnectionSocketFactory", e); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register(Protocol.HTTP.toString(), socketFactory) .register(Protocol.HTTPS.toString(), sslSocketFactory).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections()); connectionManager .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(this.config.getSocketTimeoutInMillis()) .setTcpNoDelay(true).build()); connectionManager.setMaxTotal(this.config.getMaxConnections()); return connectionManager; }
private static HttpClientConnectionManager buildHttpClientManager(int socketTimeout) { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(3); cm.setDefaultMaxPerRoute(2); cm.setValidateAfterInactivity(1); cm.setDefaultSocketConfig(SocketConfig.custom() .setSoTimeout(socketTimeout) .setSoLinger(0) .setTcpNoDelay(true) .build()); return cm; }
public static void registerConnectionManager(HttpClientConnectionManager connMgr, Long idleTimeMills){ if (instance == null) { synchronized (ApacheIdleConnectionCleaner.class) { if (instance == null) { instance = new ApacheIdleConnectionCleaner(); instance.start(); } } } connMgrMap.put(connMgr, idleTimeMills); }
private HttpClientConnectionManager createConnectionManager() { SocketConfig socketConfig = createSocketConfig(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(config.getThreadCount()); connectionManager.setDefaultMaxPerRoute(config.getThreadCount()); connectionManager.setDefaultSocketConfig(socketConfig); return connectionManager; }
private ConnectionManagerAwareHttpClient createClient(ApacheSdkHttpClientFactory configuration, AttributeMap standardOptions) { final HttpClientBuilder builder = HttpClients.custom(); // Note that it is important we register the original connection manager with the // IdleConnectionReaper as it's required for the successful deregistration of managers // from the reaper. See https://github.com/aws/aws-sdk-java/issues/722. final HttpClientConnectionManager cm = cmFactory.create(configuration, standardOptions); builder.setRequestExecutor(new HttpRequestExecutor()) // SDK handles decompression .disableContentCompression() .setKeepAliveStrategy(buildKeepAliveStrategy(configuration)) .disableRedirectHandling() .disableAutomaticRetries() .setUserAgent("") // SDK will set the user agent header in the pipeline. Don't let Apache waste time .setConnectionManager(ClientConnectionManagerFactory.wrap(cm)); addProxyConfig(builder, configuration.proxyConfiguration()); // TODO idle connection reaper // if (.useReaper()) { // IdleConnectionReaper.registerConnectionManager(cm, settings.getMaxIdleConnectionTime()); // } return new ApacheSdkClient(builder.build(), cm); }
public ApacheSdkClient(final HttpClient delegate, final HttpClientConnectionManager cm) { if (delegate == null) { throw new IllegalArgumentException("delegate " + "cannot be null"); } if (cm == null) { throw new IllegalArgumentException("connection manager " + "cannot be null"); } this.delegate = delegate; this.cm = cm; }
/** * Registers the given connection manager with this reaper; * * @param connectionManager Connection manager to register * @param maxIdleInMs Max idle connection timeout in milliseconds for this connection manager. * @return true if the connection manager has been successfully registered; false otherwise. */ public static boolean registerConnectionManager(HttpClientConnectionManager connectionManager, long maxIdleInMs) { if (instance == null) { synchronized (IdleConnectionReaper.class) { if (instance == null) { IdleConnectionReaper newInstance = new IdleConnectionReaper(); newInstance.start(); instance = newInstance; } } } return CONNECTION_MANAGERS.put(connectionManager, maxIdleInMs) == null; }
/** * Removes the given connection manager from this reaper, * and shutting down the reaper if there is zero connection manager left. * * @return true if the connection manager has been successfully removed, false otherwise. */ public static boolean removeConnectionManager(HttpClientConnectionManager connectionManager) { boolean wasRemoved = CONNECTION_MANAGERS.remove(connectionManager) != null; if (CONNECTION_MANAGERS.isEmpty()) { shutdown(); } return wasRemoved; }