@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()); }
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; }
@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); }
/** * */ 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(); }
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); } }
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(); }
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; }
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); }
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(); }
/** * 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(); }
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; }
@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(); }
@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; }
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); }
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(); }
/** * 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(); }
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(); }
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 ); }
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 ); }
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(); }
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(); }
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(); }
/** * 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(); }
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(); }
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(); }
@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(); }
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); })); }
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; }
@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); }
@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(); }
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); } }
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(); }
@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(); }
/** * @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(); }
@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(); }
@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(); }
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()); } }
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); }