List of usage examples for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS
ChannelOption CONNECT_TIMEOUT_MILLIS
To view the source code for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.
Click Source Link
From source file:com.netflix.iep.http.RxHttp.java
License:Apache License
private HttpClient<ByteBuf, ByteBuf> newClient(final RequestContext context) { final Server server = context.server(); final ClientConfig clientCfg = context.config(); HttpClient.HttpClientConfig config = new HttpClient.HttpClientConfig.Builder() .readTimeout(clientCfg.readTimeout(), TimeUnit.MILLISECONDS).userAgent(clientCfg.userAgent()) .build();/*from ww w . j a v a2 s.c o m*/ PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> pipelineCfg = new PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>>( new HttpClientPipelineConfigurator<ByteBuf, ByteBuf>(), new HttpDecompressionConfigurator()); HttpClientBuilder<ByteBuf, ByteBuf> builder = RxNetty .<ByteBuf, ByteBuf>newHttpClientBuilder(server.host(), server.port()) .pipelineConfigurator(pipelineCfg).config(config).withName(clientCfg.name()) .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, clientCfg.connectTimeout()); if (clientCfg.wireLoggingEnabled()) { builder.enableWireLogging(clientCfg.wireLoggingLevel()); } final int idleTimeout = clientCfg.idleConnectionsTimeoutMillis(); if (idleTimeout == 0) { builder.withNoConnectionPooling(); } else { builder.withConnectionPoolLimitStrategy(getPoolLimitStrategy(clientCfg)) .withIdleConnectionsTimeoutMillis(idleTimeout); } if (server.isSecure()) { builder.withSslEngineFactory(DefaultFactories.trustAll()); } return builder.build(); }
From source file:com.netflix.prana.http.api.AbstractIntegrationTest.java
License:Apache License
@Before public void setUp() { server = RxNetty.newHttpServerBuilder(0, getHandler()) .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).build(); server.start();//from w w w . j ava2 s . c o m client = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("localhost", server.getServerPort()) .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpClientConfigurator()) .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000).build(); }
From source file:com.netflix.prana.http.api.HealthCheckHandler.java
License:Apache License
private Observable<HttpClientResponse<ByteBuf>> getResponse(String externalHealthCheckURL) { String host = "localhost"; int port = DEFAULT_APPLICATION_PORT; String path = "/healthcheck"; try {//from w ww . j a v a2 s . com URL url = new URL(externalHealthCheckURL); host = url.getHost(); port = url.getPort(); path = url.getPath(); } catch (MalformedURLException e) { //continue } Integer timeout = DynamicProperty.getInstance("prana.host.healthcheck.timeout") .getInteger(DEFAULT_CONNECTION_TIMEOUT); HttpClient<ByteBuf, ByteBuf> httpClient = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(host, port) .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpClientConfigurator()) .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout).build(); return httpClient.submit(HttpClientRequest.createGet(path)); }
From source file:com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient.java
License:Apache License
@Override protected HttpClient<I, O> createRxClient(Server server) { HttpClientBuilder<I, O> clientBuilder; if (requestIdProvider != null) { clientBuilder = RxContexts.<I, O>newHttpClientBuilder(server.getHost(), server.getPort(), requestIdProvider, RxContexts.DEFAULT_CORRELATOR, pipelineConfigurator); } else {/*from ww w . j a v a 2 s . com*/ clientBuilder = RxContexts.<I, O>newHttpClientBuilder(server.getHost(), server.getPort(), RxContexts.DEFAULT_CORRELATOR, pipelineConfigurator); } Integer connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); Integer readTimeout = getProperty(IClientConfigKey.Keys.ReadTimeout, null, DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT); Boolean followRedirect = getProperty(IClientConfigKey.Keys.FollowRedirects, null, null); HttpClientConfig.Builder builder = new HttpClientConfig.Builder().readTimeout(readTimeout, TimeUnit.MILLISECONDS); if (followRedirect != null) { builder.setFollowRedirect(followRedirect); } clientBuilder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout).config(builder.build()); if (isPoolEnabled()) { clientBuilder.withConnectionPoolLimitStrategy(poolStrategy) .withIdleConnectionsTimeoutMillis(idleConnectionEvictionMills) .withPoolIdleCleanupScheduler(poolCleanerScheduler); } else { clientBuilder.withNoConnectionPooling(); } if (sslContextFactory != null) { try { SSLEngineFactory myFactory = new DefaultFactories.SSLContextBasedFactory( sslContextFactory.getSSLContext()) { @Override public SSLEngine createSSLEngine(ByteBufAllocator allocator) { SSLEngine myEngine = super.createSSLEngine(allocator); myEngine.setUseClientMode(true); return myEngine; } }; clientBuilder.withSslEngineFactory(myFactory); } catch (ClientSslSocketFactoryException e) { throw new RuntimeException(e); } } return clientBuilder.build(); }
From source file:com.netflix.ribbon.transport.netty.http.SSEClient.java
License:Apache License
@Override protected HttpClient<I, ServerSentEvent> getOrCreateRxClient(Server server) { HttpClientBuilder<I, ServerSentEvent> clientBuilder = new HttpClientBuilder<I, ServerSentEvent>( server.getHost(), server.getPort()).pipelineConfigurator(pipelineConfigurator); int requestConnectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); RxClient.ClientConfig rxClientConfig = new HttpClientConfig.Builder().build(); HttpClient<I, ServerSentEvent> client = clientBuilder .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, requestConnectTimeout).config(rxClientConfig) .build();// w w w .j av a 2 s . c om return client; }
From source file:com.netflix.ribbon.transport.netty.tcp.LoadBalancingTcpClient.java
License:Apache License
@Override protected RxClient<I, O> createRxClient(Server server) { ClientBuilder<I, O> builder = RxNetty.newTcpClientBuilder(server.getHost(), server.getPort()); if (pipelineConfigurator != null) { builder.pipelineConfigurator(pipelineConfigurator); }// w ww . j ava2 s . c o m Integer connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); builder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); if (isPoolEnabled()) { builder.withConnectionPoolLimitStrategy(poolStrategy) .withIdleConnectionsTimeoutMillis(idleConnectionEvictionMills) .withPoolIdleCleanupScheduler(poolCleanerScheduler); } else { builder.withNoConnectionPooling(); } RxClient<I, O> client = builder.build(); return client; }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException { if (isClose.get()) { throw new IOException("Closed"); }//from w w w . j a v a 2s .co m if (request.getUrl().startsWith(WEBSOCKET) && !validateWebSocketRequest(request, asyncHandler)) { throw new IOException("WebSocket method must be a GET"); } ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request); boolean useProxy = proxyServer != null; URI uri; if (useRawUrl) { uri = request.getRawURI(); } else { uri = request.getURI(); } Channel channel = null; if (useCache) { if (f != null && f.reuseChannel() && f.channel() != null) { channel = f.channel(); } else { URI connectionKeyUri = useProxy ? proxyServer.getURI() : uri; channel = lookupInCache(connectionKeyUri, request.getConnectionPoolKeyStrategy()); } } ByteBuf bufferedBytes = null; if (f != null && f.getRequest().getFile() == null && !f.getNettyRequest().getMethod().name().equals(HttpMethod.CONNECT.name())) { bufferedBytes = f.getNettyRequest().data(); } boolean useSSl = isSecure(uri) && !useProxy; if (channel != null && channel.isOpen() && channel.isActive()) { HttpRequest nettyRequest = buildRequest(config, request, uri, f == null ? false : f.isConnectAllowed(), bufferedBytes, proxyServer); if (f == null) { f = newFuture(uri, request, asyncHandler, nettyRequest, config, this, proxyServer); } else { nettyRequest = buildRequest(config, request, uri, f.isConnectAllowed(), bufferedBytes, proxyServer); f.setNettyRequest(nettyRequest); } f.setState(NettyResponseFuture.STATE.POOLED); f.attachChannel(channel, false); log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest); channel.pipeline().context(NettyAsyncHttpProvider.class).attr(DEFAULT_ATTRIBUTE).set(f); try { writeRequest(channel, config, f, nettyRequest); } catch (Exception ex) { log.debug("writeRequest failure", ex); if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) { log.debug("SSLEngine failure", ex); f = null; } else { try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("doConnect.writeRequest()", t); } IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } } return f; } // Do not throw an exception when we need an extra connection for a redirect. if (!reclaimCache && !connectionsPool.canCacheConnection()) { IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections()); try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("!connectionsPool.canCacheConnection()", t); } throw ex; } boolean acquiredConnection = false; if (trackConnections) { if (!reclaimCache) { if (!freeConnections.tryAcquire()) { IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections()); try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("!connectionsPool.canCacheConnection()", t); } throw ex; } else { acquiredConnection = true; } } } NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri); boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost()); if (useSSl) { constructSSLPipeline(c); } ChannelFuture channelFuture; Bootstrap bootstrap = request.getUrl().startsWith(WEBSOCKET) ? (useSSl ? secureWebSocketBootstrap : webSocketBootstrap) : (useSSl ? secureBootstrap : plainBootstrap); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectionTimeoutInMs()); try { InetSocketAddress remoteAddress; if (request.getInetAddress() != null) { remoteAddress = new InetSocketAddress(request.getInetAddress(), AsyncHttpProviderUtils.getPort(uri)); } else if (proxyServer == null || avoidProxy) { remoteAddress = new InetSocketAddress(AsyncHttpProviderUtils.getHost(uri), AsyncHttpProviderUtils.getPort(uri)); } else { remoteAddress = new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort()); } if (request.getLocalAddress() != null) { channelFuture = bootstrap.connect(remoteAddress, new InetSocketAddress(request.getLocalAddress(), 0)); } else { channelFuture = bootstrap.connect(remoteAddress); } } catch (Throwable t) { if (acquiredConnection) { freeConnections.release(); } abort(c.future(), t.getCause() == null ? t : t.getCause()); return c.future(); } boolean directInvokation = true; if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) { directInvokation = false; } if (directInvokation && !asyncConnect && request.getFile() == null) { int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE; if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) { if (acquiredConnection) { freeConnections.release(); } channelFuture.cancel(); abort(c.future(), new ConnectException(String.format("Connect operation to %s timeout %s", uri, timeOut))); } try { c.operationComplete(channelFuture); } catch (Exception e) { if (acquiredConnection) { freeConnections.release(); } IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); try { asyncHandler.onThrowable(ioe); } catch (Throwable t) { log.warn("c.operationComplete()", t); } throw ioe; } } else { channelFuture.addListener(c); } log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel()); if (!c.future().isCancelled() || !c.future().isDone()) { openChannels.add(channelFuture.channel()); c.future().attachChannel(channelFuture.channel(), false); } return c.future(); }
From source file:com.phei.netty.codec.msgpack.EchoClient.java
License:Apache License
public void run() throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {// w w w . j a v a 2 s . c o m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder()); ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder()); ch.pipeline().addLast(new EchoClientHandler(sendNumber)); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.phei.netty.codec.msgpack.EchoClientV2.java
License:Apache License
public void run() throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {//from w w w . jav a2 s . com Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2)); ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder()); ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2)); ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder()); ch.pipeline().addLast(new EchoClientHandler(sendNumber)); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.relayrides.pushy.apns.ApnsClient.java
License:Open Source License
/** * Sets the maximum amount of time, in milliseconds, that a client will wait to establish a connection with the * APNs server before the connection attempt is considered a failure. * * @param timeoutMillis the maximum amount of time in milliseconds to wait for a connection attempt to complete * * @since 0.5//from w w w .ja va2 s.com */ protected void setConnectionTimeout(final int timeoutMillis) { synchronized (this.bootstrap) { this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis); } }