List of usage examples for io.netty.util.concurrent Promise addListener
@Override Promise<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
From source file:org.apache.spark.sql.hive.thriftserver.rsc.Rpc.java
License:Apache License
/** * Creates an RPC client for a server running on the given remote host and port. * * @param config RPC configuration data. * @param eloop Event loop for managing the connection. * @param host Host name or IP address to connect to. * @param port Port where server is listening. * @param clientId The client ID that identifies the connection. * @param secret Secret for authenticating the client with the server. * @param dispatcher Dispatcher used to handle RPC calls. * @return A future that can be used to monitor the creation of the RPC object. *//*from ww w . j a va 2 s . c o m*/ public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception { int connectTimeoutMs = (int) config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_CONNECT_TIMEOUT); final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() { }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port); final Promise<Rpc> promise = eloop.next().newPromise(); final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>(); // Set up a timeout to undo everything. final Runnable timeoutTask = new Runnable() { @Override public void run() { promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection.")); } }; final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask, config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS); // The channel listener instantiates the Rpc instance when the connection is established, // and initiates the SASL handshake. cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture cf) throws Exception { if (cf.isSuccess()) { SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture, secret, dispatcher); Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop); saslHandler.rpc = rpc; saslHandler.sendHello(cf.channel()); } else { promise.setFailure(cf.cause()); } } }); // Handle cancellation of the promise. promise.addListener(new GenericFutureListener<Promise<Rpc>>() { @Override public void operationComplete(Promise<Rpc> p) { if (p.isCancelled()) { cf.cancel(true); } } }); return promise; }
From source file:org.kobeyoung81.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override/*from w w w. j a v a 2 s. co m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); //System.out.println(request.toString()); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); //System.out.println(request.host() +":"+ request.port()); //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080); b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:org.redisson.CommandBatchExecutorService.java
License:Apache License
public Future<List<?>> executeAsync() { if (executed) { throw new IllegalStateException("Batch already executed!"); }/*from w w w . j ava2s .co m*/ if (commands.isEmpty()) { return connectionManager.getGroup().next().newSucceededFuture(null); } executed = true; Promise<Void> voidPromise = connectionManager.newPromise(); final Promise<List<?>> promise = connectionManager.newPromise(); voidPromise.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess()) { promise.setFailure(future.cause()); return; } List<CommandEntry> entries = new ArrayList<CommandEntry>(); for (Entry e : commands.values()) { entries.addAll(e.getCommands()); } Collections.sort(entries); List<Object> result = new ArrayList<Object>(); for (CommandEntry commandEntry : entries) { result.add(commandEntry.getCommand().getPromise().getNow()); } promise.setSuccess(result); commands = null; } }); for (java.util.Map.Entry<Integer, Entry> e : commands.entrySet()) { execute(e.getValue(), e.getKey(), voidPromise, new AtomicInteger(commands.size()), 0); } return promise; }
From source file:org.redisson.CommandBatchExecutorService.java
License:Apache License
public void execute(final Entry entry, final int slot, final Promise<Void> mainPromise, final AtomicInteger slots, final int attempt) { if (!connectionManager.getShutdownLatch().acquire()) { mainPromise.setFailure(new IllegalStateException("Redisson is shutdown")); return;/*www. j a v a2 s . c o m*/ } final Promise<Void> attemptPromise = connectionManager.newPromise(); final AtomicReference<RedisException> ex = new AtomicReference<RedisException>(); final TimerTask retryTimerTask = new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (attemptPromise.isDone()) { return; } if (attempt == connectionManager.getConfig().getRetryAttempts()) { attemptPromise.setFailure(ex.get()); return; } attemptPromise.cancel(true); int count = attempt + 1; execute(entry, slot, mainPromise, slots, count); } }; try { org.redisson.client.RedisConnection connection; if (entry.isReadOnlyMode()) { connection = connectionManager.connectionReadOp(slot); } else { connection = connectionManager.connectionWriteOp(slot); } ArrayList<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(entry.getCommands().size()); for (CommandEntry c : entry.getCommands()) { list.add(c.getCommand()); } ChannelFuture future = connection.send(new CommandsData(attemptPromise, list)); ex.set(new RedisTimeoutException()); final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { timeout.cancel(); ex.set(new WriteRedisConnectionException("channel: " + future.channel() + " closed")); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } } }); if (entry.isReadOnlyMode()) { attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout)); } else { attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout)); } } catch (RedisException e) { ex.set(e); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } attemptPromise.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (future.isCancelled()) { return; } if (future.cause() instanceof RedisMovedException) { RedisMovedException ex = (RedisMovedException) future.cause(); execute(entry, ex.getSlot(), mainPromise, slots, attempt); return; } if (future.isSuccess()) { if (slots.decrementAndGet() == 0) { mainPromise.setSuccess(future.getNow()); } } else { mainPromise.setFailure(future.cause()); } } }); }
From source file:org.redisson.CommandExecutorService.java
License:Apache License
private <R, T> void retryReadRandomAsync(final RedisCommand<T> command, final Promise<R> mainPromise, final List<Integer> slots, final Object... params) { final Promise<R> attemptPromise = connectionManager.newPromise(); attemptPromise.addListener(new FutureListener<R>() { @Override/*from w ww .ja v a 2 s .c om*/ public void operationComplete(Future<R> future) throws Exception { if (future.isSuccess()) { if (future.getNow() == null) { if (slots.isEmpty()) { mainPromise.setSuccess(null); } else { retryReadRandomAsync(command, mainPromise, slots, params); } } else { mainPromise.setSuccess(future.getNow()); } } else { mainPromise.setFailure(future.cause()); } } }); Integer slot = slots.remove(0); async(true, slot, null, connectionManager.getCodec(), command, params, attemptPromise, 0); }
From source file:org.redisson.CommandExecutorService.java
License:Apache License
protected <V, R> void async(final boolean readOnlyMode, final int slot, final MultiDecoder<Object> messageDecoder, final Codec codec, final RedisCommand<V> command, final Object[] params, final Promise<R> mainPromise, final int attempt) { if (!connectionManager.getShutdownLatch().acquire()) { mainPromise.setFailure(new IllegalStateException("Redisson is shutdown")); return;/*w w w . ja v a 2 s . com*/ } final Promise<R> attemptPromise = connectionManager.newPromise(); final AtomicReference<RedisException> ex = new AtomicReference<RedisException>(); final TimerTask retryTimerTask = new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (attemptPromise.isDone()) { return; } if (attempt == connectionManager.getConfig().getRetryAttempts()) { attemptPromise.setFailure(ex.get()); return; } if (!attemptPromise.cancel(false)) { return; } int count = attempt + 1; async(readOnlyMode, slot, messageDecoder, codec, command, params, mainPromise, count); } }; try { org.redisson.client.RedisConnection connection; if (readOnlyMode) { connection = connectionManager.connectionReadOp(slot); } else { connection = connectionManager.connectionWriteOp(slot); } log.debug("getting connection for command {} via slot {} using {}", command, slot, connection.getRedisClient().getAddr()); ChannelFuture future = connection .send(new CommandData<V, R>(attemptPromise, messageDecoder, codec, command, params)); ex.set(new RedisTimeoutException()); final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { timeout.cancel(); ex.set(new WriteRedisConnectionException("Can't send command: " + command + ", params: " + params + ", channel: " + future.channel(), future.cause())); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } } }); if (readOnlyMode) { attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout)); } else { attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout)); } } catch (RedisException e) { ex.set(e); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } attemptPromise.addListener(new FutureListener<R>() { @Override public void operationComplete(Future<R> future) throws Exception { if (future.isCancelled()) { return; } // TODO cancel timeout if (future.cause() instanceof RedisMovedException) { RedisMovedException ex = (RedisMovedException) future.cause(); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); async(readOnlyMode, ex.getSlot(), messageDecoder, codec, command, params, mainPromise, attempt); return; } if (future.isSuccess()) { mainPromise.setSuccess(future.getNow()); } else { mainPromise.setFailure(future.cause()); } } }); }
From source file:org.redisson.connection.MasterSlaveConnectionManager.java
License:Apache License
private <V, T> void writeAllAsync(final int slot, final AsyncOperation<V, T> asyncOperation, final AtomicInteger counter, final Promise<T> mainPromise, final int attempt) { final Promise<T> promise = getGroup().next().newPromise(); final AtomicReference<RedisException> ex = new AtomicReference<RedisException>(); TimerTask timerTask = new TimerTask() { @Override/* w ww. j a v a 2 s . c o m*/ public void run(Timeout timeout) throws Exception { if (promise.isDone()) { return; } if (attempt == config.getRetryAttempts()) { promise.setFailure(ex.get()); return; } promise.cancel(true); int count = attempt + 1; writeAllAsync(slot, asyncOperation, counter, mainPromise, count); } }; try { RedisConnection<Object, V> connection = connectionWriteOp(slot); RedisAsyncConnection<Object, V> async = connection.getAsync(); asyncOperation.execute(promise, async); ex.set(new RedisTimeoutException()); Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); promise.addListener(createReleaseWriteListener(slot, connection, timeout)); } catch (RedisConnectionException e) { ex.set(e); timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS); } promise.addListener(new FutureListener<T>() { @Override public void operationComplete(Future<T> future) throws Exception { if (future.isCancelled()) { return; } if (future.cause() instanceof RedisMovedException) { RedisMovedException ex = (RedisMovedException) future.cause(); writeAllAsync(ex.getSlot(), asyncOperation, counter, mainPromise, attempt); return; } if (future.isSuccess()) { if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) { mainPromise.setSuccess(future.getNow()); } } else { mainPromise.setFailure(future.cause()); } } }); }
From source file:org.redisson.connection.MasterSlaveConnectionManager.java
License:Apache License
private <V, T> void writeAsync(final int slot, final AsyncOperation<V, T> asyncOperation, final Promise<T> mainPromise, final int attempt) { final Promise<T> promise = getGroup().next().newPromise(); final AtomicReference<RedisException> ex = new AtomicReference<RedisException>(); TimerTask timerTask = new TimerTask() { @Override/*w ww .j a va 2 s . c om*/ public void run(Timeout timeout) throws Exception { if (promise.isDone()) { return; } if (attempt == config.getRetryAttempts()) { promise.setFailure(ex.get()); return; } promise.cancel(true); int count = attempt + 1; writeAsync(slot, asyncOperation, mainPromise, count); } }; try { RedisConnection<Object, V> connection = connectionWriteOp(slot); RedisAsyncConnection<Object, V> async = connection.getAsync(); log.debug("writeAsync for slot {} using {}", slot, connection.getRedisClient().getAddr()); asyncOperation.execute(promise, async); ex.set(new RedisTimeoutException()); Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); promise.addListener(createReleaseWriteListener(slot, connection, timeout)); } catch (RedisConnectionException e) { ex.set(e); timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS); } promise.addListener(new FutureListener<T>() { @Override public void operationComplete(Future<T> future) throws Exception { if (future.isCancelled()) { return; } if (future.cause() instanceof RedisMovedException) { RedisMovedException ex = (RedisMovedException) future.cause(); writeAsync(ex.getSlot(), asyncOperation, mainPromise, attempt); return; } if (future.isSuccess()) { mainPromise.setSuccess(future.getNow()); } else { mainPromise.setFailure(future.cause()); } } }); }
From source file:org.redisson.connection.MasterSlaveConnectionManager.java
License:Apache License
private <V, T> void readAsync(final int slot, final AsyncOperation<V, T> asyncOperation, final Promise<T> mainPromise, final int attempt) { final Promise<T> promise = getGroup().next().newPromise(); final AtomicReference<RedisException> ex = new AtomicReference<RedisException>(); TimerTask timerTask = new TimerTask() { @Override/*from www . j a v a 2 s. c om*/ public void run(Timeout timeout) throws Exception { if (promise.isDone()) { return; } if (attempt == config.getRetryAttempts()) { promise.setFailure(ex.get()); return; } promise.cancel(true); int count = attempt + 1; readAsync(slot, asyncOperation, mainPromise, count); } }; try { RedisConnection<Object, V> connection = connectionReadOp(slot); RedisAsyncConnection<Object, V> async = connection.getAsync(); log.debug("readAsync for slot {} using {}", slot, connection.getRedisClient().getAddr()); asyncOperation.execute(promise, async); ex.set(new RedisTimeoutException()); Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); promise.addListener(createReleaseReadListener(slot, connection, timeout)); } catch (RedisConnectionException e) { ex.set(e); timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS); } promise.addListener(new FutureListener<T>() { @Override public void operationComplete(Future<T> future) throws Exception { if (future.isCancelled()) { return; } // TODO cancel timeout if (future.cause() instanceof RedisMovedException) { RedisMovedException ex = (RedisMovedException) future.cause(); readAsync(ex.getSlot(), asyncOperation, mainPromise, attempt); return; } if (future.isSuccess()) { mainPromise.setSuccess(future.getNow()); } else { mainPromise.setFailure(future.cause()); } } }); }
From source file:org.redisson.misc.ConnectionPool.java
License:Apache License
public Future<Void> add(final ClientConnectionsEntry entry) { final Promise<Void> promise = connectionManager.newPromise(); promise.addListener(new FutureListener<Void>() { @Override/* w w w.j av a 2 s . co m*/ public void operationComplete(Future<Void> future) throws Exception { entries.add(entry); } }); initConnections(entry, promise, true); return promise; }