Search in sources :

Example 1 with ConnPoolListener

use of org.apache.hc.core5.pool.ConnPoolListener in project httpcomponents-core by apache.

the class H2RequesterBootstrap method create.

public H2AsyncRequester create() {
    final ManagedConnPool<HttpHost, IOSession> connPool;
    switch(poolConcurrencyPolicy != null ? poolConcurrencyPolicy : PoolConcurrencyPolicy.STRICT) {
        case LAX:
            connPool = new LaxConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
        case STRICT:
        default:
            connPool = new StrictConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, maxTotal > 0 ? maxTotal : 50, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
    }
    final RequestHandlerRegistry<Supplier<AsyncPushConsumer>> registry = new RequestHandlerRegistry<>(uriPatternType);
    for (final HandlerEntry<Supplier<AsyncPushConsumer>> entry : pushConsumerList) {
        registry.register(entry.hostname, entry.uriPattern, entry.handler);
    }
    final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.client(), new DefaultAsyncPushConsumerFactory(registry), h2Config != null ? h2Config : H2Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, streamListener);
    final TlsStrategy actualTlsStrategy = tlsStrategy != null ? tlsStrategy : new H2ClientTlsStrategy();
    final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.client(), http1Config != null ? http1Config : Http1Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, DefaultConnectionReuseStrategy.INSTANCE, new DefaultHttpResponseParserFactory(http1Config), DefaultHttpRequestWriterFactory.INSTANCE, DefaultContentLengthStrategy.INSTANCE, DefaultContentLengthStrategy.INSTANCE, http1StreamListener);
    final IOEventHandlerFactory ioEventHandlerFactory = new ClientHttpProtocolNegotiationStarter(http1StreamHandlerFactory, http2StreamHandlerFactory, versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE, actualTlsStrategy, handshakeTimeout);
    return new H2AsyncRequester(versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE, ioReactorConfig, ioEventHandlerFactory, ioSessionDecorator, exceptionCallback, sessionListener, connPool, actualTlsStrategy, handshakeTimeout);
}
Also used : H2ClientTlsStrategy(org.apache.hc.core5.http2.ssl.H2ClientTlsStrategy) TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) DefaultDisposalCallback(org.apache.hc.core5.pool.DefaultDisposalCallback) ClientH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ClientH2StreamMultiplexerFactory) ClientHttpProtocolNegotiationStarter(org.apache.hc.core5.http2.impl.nio.ClientHttpProtocolNegotiationStarter) RequestHandlerRegistry(org.apache.hc.core5.http.protocol.RequestHandlerRegistry) DefaultAsyncPushConsumerFactory(org.apache.hc.core5.http2.nio.support.DefaultAsyncPushConsumerFactory) DefaultHttpResponseParserFactory(org.apache.hc.core5.http.impl.nio.DefaultHttpResponseParserFactory) ClientHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ClientHttp1StreamDuplexerFactory) HttpHost(org.apache.hc.core5.http.HttpHost) H2ClientTlsStrategy(org.apache.hc.core5.http2.ssl.H2ClientTlsStrategy) IOSession(org.apache.hc.core5.reactor.IOSession) Supplier(org.apache.hc.core5.function.Supplier) IOEventHandlerFactory(org.apache.hc.core5.reactor.IOEventHandlerFactory)

Example 2 with ConnPoolListener

use of org.apache.hc.core5.pool.ConnPoolListener in project httpcomponents-core by apache.

the class AsyncRequesterBootstrap method create.

public HttpAsyncRequester create() {
    final ManagedConnPool<HttpHost, IOSession> connPool;
    switch(poolConcurrencyPolicy != null ? poolConcurrencyPolicy : PoolConcurrencyPolicy.STRICT) {
        case LAX:
            connPool = new LaxConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
        case STRICT:
        default:
            connPool = new StrictConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, maxTotal > 0 ? maxTotal : 50, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
    }
    final ClientHttp1StreamDuplexerFactory streamDuplexerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.client(), http1Config != null ? http1Config : Http1Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, connStrategy, null, null, streamListener);
    final IOEventHandlerFactory ioEventHandlerFactory = new ClientHttp1IOEventHandlerFactory(streamDuplexerFactory, tlsStrategy != null ? tlsStrategy : new BasicClientTlsStrategy(), handshakeTimeout);
    return new HttpAsyncRequester(ioReactorConfig, ioEventHandlerFactory, ioSessionDecorator, exceptionCallback, sessionListener, connPool);
}
Also used : DefaultDisposalCallback(org.apache.hc.core5.pool.DefaultDisposalCallback) BasicClientTlsStrategy(org.apache.hc.core5.http.nio.ssl.BasicClientTlsStrategy) ClientHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ClientHttp1StreamDuplexerFactory) HttpHost(org.apache.hc.core5.http.HttpHost) IOSession(org.apache.hc.core5.reactor.IOSession) ClientHttp1IOEventHandlerFactory(org.apache.hc.core5.http.impl.nio.ClientHttp1IOEventHandlerFactory) IOEventHandlerFactory(org.apache.hc.core5.reactor.IOEventHandlerFactory) ClientHttp1IOEventHandlerFactory(org.apache.hc.core5.http.impl.nio.ClientHttp1IOEventHandlerFactory)

Example 3 with ConnPoolListener

use of org.apache.hc.core5.pool.ConnPoolListener in project httpcomponents-core by apache.

the class RequesterBootstrap method create.

public HttpRequester create() {
    final HttpRequestExecutor requestExecutor = new HttpRequestExecutor(HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE, connReuseStrategy != null ? connReuseStrategy : DefaultConnectionReuseStrategy.INSTANCE, streamListener);
    final ManagedConnPool<HttpHost, HttpClientConnection> connPool;
    switch(poolConcurrencyPolicy != null ? poolConcurrencyPolicy : PoolConcurrencyPolicy.STRICT) {
        case LAX:
            connPool = new LaxConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
        case STRICT:
        default:
            connPool = new StrictConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, maxTotal > 0 ? maxTotal : 50, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
    }
    return new HttpRequester(requestExecutor, httpProcessor != null ? httpProcessor : HttpProcessors.client(), connPool, socketConfig != null ? socketConfig : SocketConfig.DEFAULT, connectFactory != null ? connectFactory : new DefaultBHttpClientConnectionFactory(Http1Config.DEFAULT, CharCodingConfig.DEFAULT), sslSocketFactory, sslSetupHandler != null ? sslSetupHandler : new DefaultTlsSetupHandler(), sslSessionVerifier, DefaultAddressResolver.INSTANCE);
}
Also used : HttpRequestExecutor(org.apache.hc.core5.http.impl.io.HttpRequestExecutor) DefaultDisposalCallback(org.apache.hc.core5.pool.DefaultDisposalCallback) HttpHost(org.apache.hc.core5.http.HttpHost) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) DefaultBHttpClientConnectionFactory(org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnectionFactory) DefaultTlsSetupHandler(org.apache.hc.core5.http.io.ssl.DefaultTlsSetupHandler)

Example 4 with ConnPoolListener

use of org.apache.hc.core5.pool.ConnPoolListener in project httpcomponents-core by apache.

the class AsyncReverseProxyExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <hostname[:port]> [listener port] [--quiet]");
        System.exit(1);
    }
    // Target host
    final HttpHost targetHost = HttpHost.create(args[0]);
    int port = 8080;
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }
    for (final String s : args) {
        if ("--quiet".equalsIgnoreCase(s)) {
            quiet = true;
            break;
        }
    }
    println("Reverse proxy to " + targetHost);
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(1, TimeUnit.MINUTES).build();
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(config).setConnPoolListener(new ConnPoolListener<HttpHost>() {

        @Override
        public void onLease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] connection leased ").append(route);
            println(buf.toString());
        }

        @Override
        public void onRelease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] connection released ").append(route);
            final PoolStats totals = connPoolStats.getTotalStats();
            buf.append("; total kept alive: ").append(totals.getAvailable()).append("; ");
            buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
            buf.append(" of ").append(totals.getMax());
            println(buf.toString());
        }
    }).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
        // empty
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
        // empty
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            println("[proxy<-origin] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
        }
    }).setMaxTotal(100).setDefaultMaxPerRoute(20).create();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
        // empty
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
        // empty
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            println("[client<-proxy] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
        }
    }).register("*", () -> new IncomingExchangeHandler(targetHost, requester)).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        println("Reverse proxy shutting down");
        server.close(CloseMode.GRACEFUL);
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    server.start();
    server.listen(new InetSocketAddress(port), URIScheme.HTTP);
    println("Listening on port " + port);
    server.awaitShutdown(TimeValue.MAX_VALUE);
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) PoolStats(org.apache.hc.core5.pool.PoolStats) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) HttpHost(org.apache.hc.core5.http.HttpHost) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 5 with ConnPoolListener

use of org.apache.hc.core5.pool.ConnPoolListener in project httpcomponents-core by apache.

the class ClassicReverseProxyExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <hostname[:port]> [listener port]");
        System.exit(1);
    }
    final HttpHost targetHost = HttpHost.create(args[0]);
    int port = 8080;
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }
    System.out.println("Reverse proxy to " + targetHost);
    final HttpRequester requester = RequesterBootstrap.bootstrap().setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println("[proxy->origin] " + Thread.currentThread() + " " + request.getMethod() + " " + request.getRequestUri());
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println("[proxy<-origin] " + Thread.currentThread() + " status " + response.getCode());
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            System.out.println("[proxy<-origin] " + Thread.currentThread() + " exchange completed; " + "connection " + (keepAlive ? "kept alive" : "cannot be kept alive"));
        }
    }).setConnPoolListener(new ConnPoolListener<HttpHost>() {

        @Override
        public void onLease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] ").append(Thread.currentThread()).append(" connection leased ").append(route);
            System.out.println(buf);
        }

        @Override
        public void onRelease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] ").append(Thread.currentThread()).append(" connection released ").append(route);
            final PoolStats totals = connPoolStats.getTotalStats();
            buf.append("; total kept alive: ").append(totals.getAvailable()).append("; ");
            buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
            buf.append(" of ").append(totals.getMax());
            System.out.println(buf);
        }
    }).create();
    final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println("[client->proxy] " + Thread.currentThread() + " " + request.getMethod() + " " + request.getRequestUri());
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println("[client<-proxy] " + Thread.currentThread() + " status " + response.getCode());
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            System.out.println("[client<-proxy] " + Thread.currentThread() + " exchange completed; " + "connection " + (keepAlive ? "kept alive" : "cannot be kept alive"));
        }
    }).setExceptionListener(new ExceptionListener() {

        @Override
        public void onError(final Exception ex) {
            if (ex instanceof SocketException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
            } else {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
                ex.printStackTrace(System.out);
            }
        }

        @Override
        public void onError(final HttpConnection connection, final Exception ex) {
            if (ex instanceof SocketTimeoutException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " time out");
            } else if (ex instanceof SocketException || ex instanceof ConnectionClosedException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
            } else {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
                ex.printStackTrace(System.out);
            }
        }
    }).register("*", new ProxyHandler(targetHost, requester)).create();
    server.start();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        server.close(CloseMode.GRACEFUL);
        requester.close(CloseMode.GRACEFUL);
    }));
    System.out.println("Listening on port " + port);
    server.awaitTermination(TimeValue.MAX_VALUE);
}
Also used : BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) PoolStats(org.apache.hc.core5.pool.PoolStats) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) SocketTimeoutException(java.net.SocketTimeoutException) HttpHost(org.apache.hc.core5.http.HttpHost) ConnPoolListener(org.apache.hc.core5.pool.ConnPoolListener) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) ExceptionListener(org.apache.hc.core5.http.ExceptionListener) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester)

Aggregations

HttpHost (org.apache.hc.core5.http.HttpHost)5 DefaultDisposalCallback (org.apache.hc.core5.pool.DefaultDisposalCallback)3 HttpConnection (org.apache.hc.core5.http.HttpConnection)2 HttpRequest (org.apache.hc.core5.http.HttpRequest)2 HttpResponse (org.apache.hc.core5.http.HttpResponse)2 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)2 ClientHttp1StreamDuplexerFactory (org.apache.hc.core5.http.impl.nio.ClientHttp1StreamDuplexerFactory)2 ConnPoolStats (org.apache.hc.core5.pool.ConnPoolStats)2 PoolStats (org.apache.hc.core5.pool.PoolStats)2 IOEventHandlerFactory (org.apache.hc.core5.reactor.IOEventHandlerFactory)2 IOSession (org.apache.hc.core5.reactor.IOSession)2 IOException (java.io.IOException)1 InetSocketAddress (java.net.InetSocketAddress)1 SocketException (java.net.SocketException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 Supplier (org.apache.hc.core5.function.Supplier)1 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)1 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)1 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)1 ExceptionListener (org.apache.hc.core5.http.ExceptionListener)1