List of usage examples for io.netty.util TimerTask TimerTask
TimerTask
From source file:org.redisson.command.RedisExecutor.java
License:Apache License
private void scheduleRetryTimeout(RFuture<RedisConnection> connectionFuture, RPromise<R> attemptPromise) { if (retryInterval == 0 || attempts == 0) { this.timeout = MasterSlaveConnectionManager.DUMMY_TIMEOUT; return;/* w w w.j a va 2s .co m*/ } TimerTask retryTimerTask = new TimerTask() { @Override public void run(Timeout t) throws Exception { if (attemptPromise.isDone()) { return; } if (connectionFuture.cancel(false)) { if (exception == null) { exception = new RedisTimeoutException( "Unable to get connection! Try to increase 'nettyThreads' and/or connection pool size settings" + "Node source: " + source + ", command: " + LogHelper.toString(command, params) + " after " + attempt + " retry attempts"); } } else { if (connectionFuture.isSuccess()) { if (writeFuture == null || !writeFuture.isDone()) { if (attempt == attempts) { if (writeFuture != null && writeFuture.cancel(false)) { if (exception == null) { exception = new RedisTimeoutException( "Unable to send command! Try to increase 'nettyThreads' and/or connection pool size settings " + "Node source: " + source + ", connection: " + connectionFuture.getNow() + ", command: " + LogHelper.toString(command, params) + " after " + attempts + " retry attempts"); } attemptPromise.tryFailure(exception); } return; } attempt++; Timeout timeout; if (retryInterval > 0 && attempts > 0) { timeout = connectionManager.newTimeout(this, retryInterval, TimeUnit.MILLISECONDS); } else { timeout = MasterSlaveConnectionManager.DUMMY_TIMEOUT; } RedisExecutor.this.timeout = timeout; return; } if (writeFuture.isDone() && writeFuture.isSuccess()) { return; } } } if (mainPromise.isCancelled()) { if (attemptPromise.cancel(false)) { free(); } return; } if (attempt == attempts) { if (exception == null) { exception = new RedisTimeoutException( "Unable to send command! Try to increase 'nettyThreads' and/or connection pool size settings. Node source: " + source + ", command: " + LogHelper.toString(command, params) + " after " + attempts + " retry attempts"); } attemptPromise.tryFailure(exception); return; } if (!attemptPromise.cancel(false)) { return; } attempt++; if (log.isDebugEnabled()) { log.debug("attempt {} for command {} and params {}", attempt, command, LogHelper.toString(params)); } mainPromiseListener = null; execute(); } }; timeout = connectionManager.newTimeout(retryTimerTask, retryInterval, TimeUnit.MILLISECONDS); }
From source file:org.redisson.command.RedisExecutor.java
License:Apache License
private void checkWriteFuture(ChannelFuture future, RPromise<R> attemptPromise, RedisConnection connection) { if (future.isCancelled() || attemptPromise.isDone()) { return;/*from w ww . j a v a2 s. com*/ } if (!future.isSuccess()) { exception = new WriteRedisConnectionException( "Unable to send command! Node source: " + source + ", connection: " + connection + ", command: " + LogHelper.toString(command, params) + " after " + attempt + " retry attempts", future.cause()); if (attempt == attempts) { if (!attemptPromise.tryFailure(exception)) { log.error(exception.getMessage()); } } return; } timeout.cancel(); long timeoutTime = responseTimeout; if (command != null && (RedisCommands.BLOCKING_COMMAND_NAMES.contains(command.getName()) || RedisCommands.BLOCKING_COMMANDS.contains(command))) { Long popTimeout = null; if (RedisCommands.BLOCKING_COMMANDS.contains(command)) { boolean found = false; for (Object param : params) { if (found) { popTimeout = Long.valueOf(param.toString()) / 1000; break; } if ("BLOCK".equals(param)) { found = true; } } } else { popTimeout = Long.valueOf(params[params.length - 1].toString()); } handleBlockingOperations(attemptPromise, connection, popTimeout); if (popTimeout == 0) { return; } timeoutTime += popTimeout * 1000; // add 1 second due to issue https://github.com/antirez/redis/issues/874 timeoutTime += 1000; } long timeoutAmount = timeoutTime; TimerTask timeoutTask = new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (attempt < attempts) { if (!attemptPromise.cancel(false)) { return; } attempt++; if (log.isDebugEnabled()) { log.debug("attempt {} for command {} and params {}", attempt, command, LogHelper.toString(params)); } mainPromiseListener = null; execute(); return; } attemptPromise.tryFailure(new RedisResponseTimeoutException("Redis server response timeout (" + timeoutAmount + " ms) occured" + " after " + attempts + " retry attempts. Command: " + LogHelper.toString(command, params) + ", channel: " + connection.getChannel())); } }; timeout = connectionManager.newTimeout(timeoutTask, timeoutTime, TimeUnit.MILLISECONDS); }
From source file:org.redisson.command.RedisExecutor.java
License:Apache License
private void handleBlockingOperations(RPromise<R> attemptPromise, RedisConnection connection, Long popTimeout) { FutureListener<Void> listener = f -> { mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown")); };/*from ww w . j a va 2 s. com*/ Timeout scheduledFuture; if (popTimeout != 0) { // handling cases when connection has been lost scheduledFuture = connectionManager.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (attemptPromise.trySuccess(null)) { connection.forceFastReconnectAsync(); } } }, popTimeout, TimeUnit.SECONDS); } else { scheduledFuture = null; } mainPromise.onComplete((res, e) -> { if (scheduledFuture != null) { scheduledFuture.cancel(); } synchronized (listener) { connectionManager.getShutdownPromise().removeListener(listener); } // handling cancel operation for blocking commands if (mainPromise.isCancelled() && !attemptPromise.isDone()) { log.debug("Canceled blocking operation {} used {}", command, connection); connection.forceFastReconnectAsync().onComplete((r, ex) -> { attemptPromise.cancel(true); }); return; } if (e instanceof RedissonShutdownException) { attemptPromise.tryFailure(e); } }); synchronized (listener) { if (!mainPromise.isDone()) { connectionManager.getShutdownPromise().addListener(listener); } } }
From source file:org.redisson.command.RedisExecutor.java
License:Apache License
protected void checkAttemptPromise(RPromise<R> attemptFuture, RFuture<RedisConnection> connectionFuture) { timeout.cancel();/*from w w w. jav a 2 s. com*/ if (attemptFuture.isCancelled()) { return; } try { mainPromiseListener = null; if (attemptFuture.cause() instanceof RedisMovedException && !ignoreRedirect) { RedisMovedException ex = (RedisMovedException) attemptFuture.cause(); if (source.getRedirect() == Redirect.MOVED) { mainPromise.tryFailure(new RedisException("MOVED redirection loop detected. Node " + source.getAddr() + " has further redirect to " + ex.getUrl())); return; } onException(); source = new NodeSource(ex.getSlot(), connectionManager.applyNatMap(ex.getUrl()), Redirect.MOVED); execute(); return; } if (attemptFuture.cause() instanceof RedisAskException && !ignoreRedirect) { RedisAskException ex = (RedisAskException) attemptFuture.cause(); onException(); source = new NodeSource(ex.getSlot(), connectionManager.applyNatMap(ex.getUrl()), Redirect.ASK); execute(); return; } if (attemptFuture.cause() instanceof RedisLoadingException || attemptFuture.cause() instanceof RedisTryAgainException) { if (attempt < attempts) { onException(); connectionManager.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { attempt++; execute(); } }, Math.min(responseTimeout, 1000), TimeUnit.MILLISECONDS); return; } } free(); handleResult(attemptFuture, connectionFuture); } catch (Exception e) { handleError(connectionFuture, e); } }
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;/*from w ww . ja v a 2s . 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
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;/*from w ww .ja va 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/*from w w w .ja 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; 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/*from w w w . ja 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; 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 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; 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.connection.pool.ConnectionPool.java
License:Apache License
private void scheduleCheck(final ClientConnectionsEntry entry) { connectionManager.getConnectionEventsHub().fireDisconnect(entry.getClient().getAddr()); connectionManager.newTimeout(new TimerTask() { @Override//from www . ja v a2s.c om public void run(Timeout timeout) throws Exception { if (entry.getFreezeReason() != FreezeReason.RECONNECT || !entry.isFreezed()) { return; } RFuture<RedisConnection> connectionFuture = entry.getClient().connectAsync(); connectionFuture.addListener(new FutureListener<RedisConnection>() { @Override public void operationComplete(Future<RedisConnection> future) throws Exception { if (entry.getFreezeReason() != FreezeReason.RECONNECT || !entry.isFreezed()) { return; } if (!future.isSuccess()) { scheduleCheck(entry); return; } final RedisConnection c = future.getNow(); if (!c.isActive()) { c.closeAsync(); scheduleCheck(entry); return; } final FutureListener<String> pingListener = new FutureListener<String>() { @Override public void operationComplete(Future<String> future) throws Exception { try { if (entry.getFreezeReason() != FreezeReason.RECONNECT || !entry.isFreezed()) { return; } if (future.isSuccess() && "PONG".equals(future.getNow())) { entry.resetFailedAttempts(); RPromise<Void> promise = connectionManager.newPromise(); promise.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (entry.getNodeType() == NodeType.SLAVE) { masterSlaveEntry.slaveUp( entry.getClient().getAddr().getHostName(), entry.getClient().getAddr().getPort(), FreezeReason.RECONNECT); log.info("slave {} successfully reconnected", entry.getClient().getAddr()); } else { synchronized (entry) { if (entry.getFreezeReason() == FreezeReason.RECONNECT) { entry.setFreezed(false); entry.setFreezeReason(null); log.info("host {} successfully reconnected", entry.getClient().getAddr()); } } } } }); initConnections(entry, promise, false); } else { scheduleCheck(entry); } } finally { c.closeAsync(); } } }; if (entry.getConfig().getPassword() != null) { RFuture<Void> temp = c.async(RedisCommands.AUTH, config.getPassword()); FutureListener<Void> listener = new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { ping(c, pingListener); } }; temp.addListener(listener); } else { ping(c, pingListener); } } }); } }, config.getReconnectionTimeout(), TimeUnit.MILLISECONDS); }