List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:org.redisson.command.RedisExecutor.java
License:Apache License
public void execute() { if (mainPromise.isCancelled()) { free();/*from ww w . ja v a 2 s. c o m*/ return; } if (!connectionManager.getShutdownLatch().acquire()) { free(); mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown")); return; } codec = getCodec(codec); RFuture<RedisConnection> connectionFuture = getConnection(); RPromise<R> attemptPromise = new RedissonPromise<R>(); mainPromiseListener = (r, e) -> { if (mainPromise.isCancelled() && connectionFuture.cancel(false)) { log.debug("Connection obtaining canceled for {}", command); timeout.cancel(); if (attemptPromise.cancel(false)) { free(); } } }; if (attempt == 0) { mainPromise.onComplete((r, e) -> { if (this.mainPromiseListener != null) { this.mainPromiseListener.accept(r, e); } }); } scheduleRetryTimeout(connectionFuture, attemptPromise); connectionFuture.onComplete((connection, e) -> { if (connectionFuture.isCancelled()) { connectionManager.getShutdownLatch().release(); return; } if (!connectionFuture.isSuccess()) { connectionManager.getShutdownLatch().release(); exception = convertException(connectionFuture); return; } if (attemptPromise.isDone() || mainPromise.isDone()) { releaseConnection(attemptPromise, connectionFuture); return; } sendCommand(attemptPromise, connection); writeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { checkWriteFuture(writeFuture, attemptPromise, connection); } }); releaseConnection(attemptPromise, connectionFuture); }); attemptPromise.onComplete((r, e) -> { checkAttemptPromise(attemptPromise, connectionFuture); }); }
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;//ww w . j a v a 2 s .com } 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
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. j av a2 s . c om } 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.pubsub.PublishSubscribeService.java
License:Apache License
private void subscribe(Codec codec, ChannelName channelName, RPromise<PubSubConnectionEntry> promise, PubSubType type, AsyncSemaphore lock, RedisPubSubListener<?>... listeners) { PubSubConnectionEntry connEntry = name2PubSubConnection.get(channelName); if (connEntry != null) { addListeners(channelName, promise, type, lock, connEntry, listeners); return;/*from w ww. j a v a 2 s . c om*/ } freePubSubLock.acquire(new Runnable() { @Override public void run() { if (promise.isDone()) { lock.release(); freePubSubLock.release(); return; } PubSubConnectionEntry freeEntry = freePubSubConnections.peek(); if (freeEntry == null) { connect(codec, channelName, promise, type, lock, listeners); return; } int remainFreeAmount = freeEntry.tryAcquire(); if (remainFreeAmount == -1) { throw new IllegalStateException(); } PubSubConnectionEntry oldEntry = name2PubSubConnection.putIfAbsent(channelName, freeEntry); if (oldEntry != null) { freeEntry.release(); freePubSubLock.release(); addListeners(channelName, promise, type, lock, oldEntry, listeners); return; } if (remainFreeAmount == 0) { freePubSubConnections.poll(); } freePubSubLock.release(); RFuture<Void> subscribeFuture = addListeners(channelName, promise, type, lock, freeEntry, listeners); ChannelFuture future; if (PubSubType.PSUBSCRIBE == type) { future = freeEntry.psubscribe(codec, channelName); } else { future = freeEntry.subscribe(codec, channelName); } future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { if (!promise.isDone()) { subscribeFuture.cancel(false); } return; } connectionManager.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { subscribeFuture.cancel(false); } }, config.getTimeout(), TimeUnit.MILLISECONDS); } }); } }); }
From source file:org.redisson.pubsub.PublishSubscribeService.java
License:Apache License
private void connect(Codec codec, ChannelName channelName, RPromise<PubSubConnectionEntry> promise, PubSubType type, AsyncSemaphore lock, RedisPubSubListener<?>... listeners) { int slot = connectionManager.calcSlot(channelName.getName()); RFuture<RedisPubSubConnection> connFuture = nextPubSubConnection(slot); promise.onComplete((res, e) -> {/* w ww .j a v a 2 s . c om*/ if (e != null) { ((RPromise<RedisPubSubConnection>) connFuture).tryFailure(e); } }); connFuture.onComplete((conn, e) -> { if (e != null) { freePubSubLock.release(); lock.release(); promise.tryFailure(e); return; } PubSubConnectionEntry entry = new PubSubConnectionEntry(conn, config.getSubscriptionsPerConnection()); int remainFreeAmount = entry.tryAcquire(); PubSubConnectionEntry oldEntry = name2PubSubConnection.putIfAbsent(channelName, entry); if (oldEntry != null) { releaseSubscribeConnection(slot, entry); freePubSubLock.release(); addListeners(channelName, promise, type, lock, oldEntry, listeners); return; } if (remainFreeAmount > 0) { freePubSubConnections.add(entry); } freePubSubLock.release(); RFuture<Void> subscribeFuture = addListeners(channelName, promise, type, lock, entry, listeners); ChannelFuture future; if (PubSubType.PSUBSCRIBE == type) { future = entry.psubscribe(codec, channelName); } else { future = entry.subscribe(codec, channelName); } future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { if (!promise.isDone()) { subscribeFuture.cancel(false); } return; } connectionManager.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { subscribeFuture.cancel(false); } }, config.getTimeout(), TimeUnit.MILLISECONDS); } }); }); }
From source file:org.redisson.pubsub.PublishSubscribeService.java
License:Apache License
public RFuture<Void> unsubscribe(ChannelName channelName, AsyncSemaphore lock) { PubSubConnectionEntry entry = name2PubSubConnection.remove(channelName); if (entry == null || connectionManager.isShuttingDown()) { lock.release();/*w ww .ja v a2 s . c o m*/ return RedissonPromise.newSucceededFuture(null); } AtomicBoolean executed = new AtomicBoolean(); RedissonPromise<Void> result = new RedissonPromise<Void>(); ChannelFuture future = entry.unsubscribe(channelName, new BaseRedisPubSubListener() { @Override public boolean onStatus(PubSubType type, CharSequence channel) { if (type == PubSubType.UNSUBSCRIBE && channel.equals(channelName)) { executed.set(true); if (entry.release() == 1) { freePubSubConnections.add(entry); } lock.release(); result.trySuccess(null); return true; } return false; } }); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { return; } connectionManager.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (executed.get()) { return; } entry.getConnection() .onMessage(new PubSubStatusMessage(PubSubType.UNSUBSCRIBE, channelName)); } }, config.getTimeout(), TimeUnit.MILLISECONDS); } }); return result; }
From source file:org.redisson.pubsub.PublishSubscribeService.java
License:Apache License
public RFuture<Codec> unsubscribe(ChannelName channelName, PubSubType topicType) { if (connectionManager.isShuttingDown()) { return RedissonPromise.newSucceededFuture(null); }/*from w w w .j a v a 2 s. c o m*/ RPromise<Codec> result = new RedissonPromise<>(); AsyncSemaphore lock = getSemaphore(channelName); lock.acquire(new Runnable() { @Override public void run() { PubSubConnectionEntry entry = name2PubSubConnection.remove(channelName); if (entry == null) { lock.release(); result.trySuccess(null); return; } freePubSubLock.acquire(new Runnable() { @Override public void run() { freePubSubConnections.remove(entry); freePubSubLock.release(); Codec entryCodec; if (topicType == PubSubType.PUNSUBSCRIBE) { entryCodec = entry.getConnection().getPatternChannels().get(channelName); } else { entryCodec = entry.getConnection().getChannels().get(channelName); } AtomicBoolean executed = new AtomicBoolean(); RedisPubSubListener<Object> listener = new BaseRedisPubSubListener() { @Override public boolean onStatus(PubSubType type, CharSequence channel) { if (type == topicType && channel.equals(channelName)) { executed.set(true); lock.release(); result.trySuccess(entryCodec); return true; } return false; } }; ChannelFuture future; if (topicType == PubSubType.PUNSUBSCRIBE) { future = entry.punsubscribe(channelName, listener); } else { future = entry.unsubscribe(channelName, listener); } future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { return; } connectionManager.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (executed.get()) { return; } entry.getConnection() .onMessage(new PubSubStatusMessage(topicType, channelName)); } }, config.getTimeout(), TimeUnit.MILLISECONDS); } }); } }); } }); return result; }
From source file:org.robotbrains.support.web.server.netty.NettyWebServerHandler.java
License:Apache License
/** * Is the HTTP request requesting a Web Socket protocol upgrade? * * @param context/*from w w w. ja v a2 s . com*/ * the request context * @param request * the HTTP request * @param user * the user making the request * * @return {@code true} if a Web Socket protocol upgrade */ private boolean tryWebSocketUpgradeRequest(ChannelHandlerContext context, HttpRequest request, final String user) { if (!request.getUri().startsWith(fullWebSocketUriPrefix)) { return false; } if (accessManager != null) { if (!accessManager.userHasAccess(user, request.getUri())) { return false; } } // Handshake WebSocketServerHandshakerFactory wsFactory = getWebSocketHandshakerFactory(request); final ChannelWithId channel = (ChannelWithId) context.channel(); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel); } else { ChannelFuture handshake = handshaker.handshake(channel, request); handshake.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { completeWebSocketHandshake(user, channel, handshaker); } }); } // Handled request. return true; }
From source file:org.robotninjas.protobuf.netty.server.RpcServer.java
License:Open Source License
@Override protected void doStart() { try {/*from ww w . j ava2s.com*/ ChannelFuture f = bootstrap.bind(address); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { Channel serverChannel = future.channel(); allChannels.add(serverChannel); notifyStarted(); } else { notifyFailed(future.cause()); } } }); } catch (Throwable t) { notifyFailed(t); Throwables.propagate(t); } }
From source file:org.royaldev.enterprise.proxy.ProxyBackendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { this.showHierarchy(msg.getClass()); if (msg instanceof ByteBuf) { final ByteBuf bf = (ByteBuf) msg; /*final GenericPacket gp = new GenericPacket(bf); switch (gp.getID()) {/*w w w . ja va 2 s. c om*/ case PacketType.Server.CHAT: final ServerPacket04Chat spc = new ServerPacket04Chat(gp); break; }*/ bf.resetReaderIndex(); } inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) ctx.channel().read(); else future.channel().close(); } }); }