List of usage examples for io.netty.channel ChannelFuture cancel
@Override boolean cancel(boolean mayInterruptIfRunning);
From source file:com.weibo.api.motan.transport.netty.NettyChannel.java
License:Apache License
@Override public Response request(Request request) throws TransportException { int timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); }//from w ww . j a v a 2s.com NettyResponseFuture response = new NettyResponseFuture(request, timeout, this.nettyClient); this.nettyClient.registerCallback(request.getRequestId(), response); ChannelFuture writeFuture = this.channel.writeAndFlush(request); boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS); if (result && writeFuture.isSuccess()) { response.addListener(new FutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess() || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) { // ? nettyClient.resetErrorCount(); } else { // nettyClient.incrErrorCount(); } } }); return response; } writeFuture.cancel(false); response = this.nettyClient.removeCallback(request.getRequestId()); if (response != null) { response.cancel(); } // nettyClient.incrErrorCount(); if (writeFuture.cause() != null) { throw new MotanServiceException( "NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request), writeFuture.cause()); } else { throw new MotanServiceException( "NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request)); } }
From source file:com.weibo.api.motan.transport.netty.NettyChannel.java
License:Apache License
@Override public synchronized boolean open() { if (isAvailable()) { LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri()); return true; }//from ww w.jav a 2 s .c o m try { ChannelFuture channleFuture = nettyClient.getBootstrap() .connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort())); long start = System.currentTimeMillis(); int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException( "NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } // ??connectTimeout boolean result = channleFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS); boolean success = channleFuture.isSuccess(); if (result && success) { channel = channleFuture.channel(); if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) channel.localAddress(); } state = ChannelState.ALIVE; return true; } boolean connected = false; if (channleFuture.channel() != null) { connected = channleFuture.channel().isActive(); } if (channleFuture.cause() != null) { channleFuture.cancel(false); throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channleFuture.cause()); } else { channleFuture.cancel(false); throw new MotanServiceException("NettyChannel connect to server timeout url: " + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected); } } catch (MotanServiceException e) { throw e; } catch (Exception e) { throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e); } finally { if (!state.isAliveState()) { nettyClient.incrErrorCount(); } } }
From source file:com.weibo.api.motan.transport.netty4.client.NettyChannel.java
License:Apache License
@Override public Response request(Request request) throws TransportException { int timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException("Netty4Client init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); }/* ww w. jav a2 s .com*/ NettyResponseFuture response = new NettyResponseFuture(request, timeout, this.nettyClient); this.nettyClient.registerCallback(request.getRequestId(), response); ChannelFuture writeFuture = this.channel.writeAndFlush(request); boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.SECONDS); if (result && writeFuture.isSuccess()) { response.addListener(new FutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess() || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) { // ? nettyClient.resetErrorCount(); } else { // nettyClient.incrErrorCount(); } } }); return response; } writeFuture.cancel(true); response = this.nettyClient.removeCallback(request.getRequestId()); if (response != null) { response.cancel(); } // nettyClient.incrErrorCount(); if (writeFuture.cause() != null) { throw new MotanServiceException( "NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request), writeFuture.cause()); } else { throw new MotanServiceException( "NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request)); } }
From source file:com.weibo.api.motan.transport.netty4.client.NettyChannel.java
License:Apache License
@Override public synchronized boolean open() { if (isAvailable()) { LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri()); return true; }//from w w w . j av a2s.c o m try { ChannelFuture channelFuture = nettyClient.getBootstrap() .connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort())); long start = System.currentTimeMillis(); int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException( "Netty4Client init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } // ??connectTimeout boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS); boolean success = channelFuture.isSuccess(); if (result && success) { channel = channelFuture.channel(); if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) channel.localAddress(); } state = ChannelState.ALIVE; return true; } boolean connected = false; if (channelFuture.channel() != null) { connected = channelFuture.channel().isOpen(); } if (channelFuture.cause() != null) { channelFuture.cancel(true); throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channelFuture.cause()); } else { channelFuture.cancel(true); throw new MotanServiceException("NettyChannel connect to server timeout url: " + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected); } } catch (MotanServiceException e) { throw e; } catch (Exception e) { throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e); } finally { if (!state.isAliveState()) { nettyClient.incrErrorCount(); } } }
From source file:io.lettuce.core.AbstractRedisClient.java
License:Apache License
private void initializeChannelAsync0(ConnectionBuilder connectionBuilder, CompletableFuture<Channel> channelReadyFuture, SocketAddress redisAddress) { logger.debug("Connecting to Redis at {}", redisAddress); Bootstrap redisBootstrap = connectionBuilder.bootstrap(); RedisChannelInitializer initializer = connectionBuilder.build(); redisBootstrap.handler(initializer); clientResources.nettyCustomizer().afterBootstrapInitialized(redisBootstrap); CompletableFuture<Boolean> initFuture = initializer.channelInitialized(); ChannelFuture connectFuture = redisBootstrap.connect(redisAddress); channelReadyFuture.whenComplete((c, t) -> { if (t instanceof CancellationException) { connectFuture.cancel(true); initFuture.cancel(true);/*from w w w .j a va 2 s.co m*/ } }); connectFuture.addListener(future -> { if (!future.isSuccess()) { logger.debug("Connecting to Redis at {}: {}", redisAddress, future.cause()); connectionBuilder.endpoint().initialState(); channelReadyFuture.completeExceptionally(future.cause()); return; } initFuture.whenComplete((success, throwable) -> { if (throwable == null) { logger.debug("Connecting to Redis at {}: Success", redisAddress); RedisChannelHandler<?, ?> connection = connectionBuilder.connection(); connection.registerCloseables(closeableResources, connection); channelReadyFuture.complete(connectFuture.channel()); return; } logger.debug("Connecting to Redis at {}, initialization: {}", redisAddress, throwable); connectionBuilder.endpoint().initialState(); Throwable failure; if (throwable instanceof RedisConnectionException) { failure = throwable; } else if (throwable instanceof TimeoutException) { failure = new RedisConnectionException( "Could not initialize channel within " + connectionBuilder.getTimeout(), throwable); } else { failure = throwable; } channelReadyFuture.completeExceptionally(failure); }); }); }
From source file:io.lettuce.core.protocol.ReconnectionHandler.java
License:Apache License
private void reconnect0(CompletableFuture<Channel> result, SocketAddress remoteAddress) { ChannelFuture connectFuture = bootstrap.connect(remoteAddress); ChannelPromise initFuture = connectFuture.channel().newPromise(); logger.debug("Reconnecting to Redis at {}", remoteAddress); result.whenComplete((c, t) -> {/* w w w .ja v a 2 s .c om*/ if (t instanceof CancellationException) { connectFuture.cancel(true); initFuture.cancel(true); } }); initFuture.addListener((ChannelFuture it) -> { if (it.cause() != null) { connectFuture.cancel(true); close(it.channel()); result.completeExceptionally(it.cause()); } else { result.complete(connectFuture.channel()); } }); connectFuture.addListener((ChannelFuture it) -> { if (it.cause() != null) { initFuture.tryFailure(it.cause()); return; } ChannelPipeline pipeline = it.channel().pipeline(); RedisChannelInitializer channelInitializer = pipeline.get(RedisChannelInitializer.class); if (channelInitializer == null) { initFuture.tryFailure(new IllegalStateException( "Reconnection attempt without a RedisChannelInitializer in the channel pipeline")); return; } channelInitializer.channelInitialized().whenComplete((state, throwable) -> { if (throwable != null) { if (isExecutionException(throwable)) { initFuture.tryFailure(throwable); return; } if (clientOptions.isCancelCommandsOnReconnectFailure()) { connectionFacade.reset(); } if (clientOptions.isSuspendReconnectOnProtocolFailure()) { logger.error("Disabling autoReconnect due to initialization failure", throwable); setReconnectSuspended(true); } initFuture.tryFailure(throwable); return; } if (logger.isDebugEnabled()) { logger.info("Reconnected to {}, Channel {}", remoteAddress, ChannelLogDescriptor.logDescriptor(it.channel())); } else { logger.info("Reconnected to {}", remoteAddress); } initFuture.trySuccess(); }); }); Runnable timeoutAction = () -> { initFuture.tryFailure(new TimeoutException( String.format("Reconnection attempt exceeded timeout of %d %s ", timeout, timeoutUnit))); }; Timeout timeoutHandle = timer.newTimeout(it -> { if (connectFuture.isDone() && initFuture.isDone()) { return; } if (reconnectWorkers.isShutdown()) { timeoutAction.run(); return; } reconnectWorkers.submit(timeoutAction); }, this.timeout, timeoutUnit); initFuture.addListener(it -> timeoutHandle.cancel()); }
From source file:io.reactivex.netty.client.ClientChannelFactoryImpl.java
License:Apache License
@Override public ChannelFuture connect(final Subscriber<? super ObservableConnection<I, O>> subscriber, RxClient.ServerInfo serverInfo,/*w w w .j av a 2 s.com*/ final ClientConnectionFactory<I, O, ? extends ObservableConnection<I, O>> connectionFactory) { final long startTimeMillis = Clock.newStartTimeMillis(); eventsSubject.onEvent(ClientMetricsEvent.CONNECT_START); final ChannelFuture connectFuture = clientBootstrap.connect(serverInfo.getHost(), serverInfo.getPort()); subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { if (!connectFuture.isDone()) { connectFuture.cancel(true); // Unsubscribe here means, no more connection is required. A close on connection is explicit. } } })); connectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { if (!future.isSuccess()) { eventsSubject.onEvent(ClientMetricsEvent.CONNECT_FAILED, Clock.onEndMillis(startTimeMillis), future.cause()); subscriber.onError(future.cause()); } else { eventsSubject.onEvent(ClientMetricsEvent.CONNECT_SUCCESS, Clock.onEndMillis(startTimeMillis)); ChannelPipeline pipeline = future.channel().pipeline(); ChannelHandlerContext ctx = pipeline.lastContext(); // The connection uses the context for write which should always start from the tail. final ObservableConnection<I, O> newConnection = connectionFactory.newConnection(ctx); ChannelHandler lifecycleHandler = pipeline .get(RxRequiredConfigurator.CONN_LIFECYCLE_HANDLER_NAME); if (null == lifecycleHandler) { onNewConnection(newConnection, subscriber); } else { @SuppressWarnings("unchecked") ConnectionLifecycleHandler<I, O> handler = (ConnectionLifecycleHandler<I, O>) lifecycleHandler; SslHandler sslHandler = pipeline.get(SslHandler.class); if (null == sslHandler) { handler.setConnection(newConnection); onNewConnection(newConnection, subscriber); } else { sslHandler.handshakeFuture() .addListener(new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete(Future<? super Channel> future) throws Exception { onNewConnection(newConnection, subscriber); } }); } } } } catch (Throwable throwable) { subscriber.onError(throwable); } } }); return connectFuture; }
From source file:io.reactivex.netty.client.ClientConnectionHandler.java
License:Apache License
void connectionAttempted(final ChannelFuture connectFuture) { connectionSub.add(Subscriptions.create(new Action0() { @Override/*from w w w. jav a2s . c o m*/ public void call() { if (!connectFuture.isDone()) { connectFuture.cancel(true); // Unsubscribe here means, no more connection is required. A close on connection is explicit. } } })); }
From source file:io.reactivex.netty.protocol.http.MultipleFutureListener.java
License:Apache License
public void cancelPendingFutures(boolean mayInterruptIfRunning) { for (Iterator<ChannelFuture> iterator = pendingFutures.iterator(); iterator.hasNext();) { ChannelFuture pendingFuture = iterator.next(); iterator.remove();/*from w w w .ja v a 2 s . c om*/ pendingFuture.cancel(mayInterruptIfRunning); } }
From source file:net.tomp2p.connection.Sender.java
License:Apache License
/** * @param channelFuture/*from www .j a v a 2 s. c o m*/ * The channel future that can be canceled * @return Create a cancel class for the channel future */ private static Cancel createCancel(final ChannelFuture channelFuture) { return new Cancel() { @Override public void cancel() { channelFuture.cancel(true); } }; }