List of usage examples for io.netty.util.concurrent Future getNow
V getNow();
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 ww . j av a2 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 w ww . j ava2 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 createConnection(final boolean checkFreezed, final AtomicInteger requests, final ClientConnectionsEntry entry, final RPromise<Void> initPromise, final int minimumIdleSize, final AtomicInteger initializedConnections) { if ((checkFreezed && entry.isFreezed()) || !tryAcquireConnection(entry)) { Throwable cause = new RedisConnectionException("Can't init enough connections amount! Only " + (minimumIdleSize - initializedConnections.get()) + " from " + minimumIdleSize + " were initialized. Server: " + entry.getClient().getAddr()); initPromise.tryFailure(cause);/*from w w w . ja va2 s . c o m*/ return; } acquireConnection(entry, new Runnable() { @Override public void run() { RPromise<T> promise = connectionManager.newPromise(); createConnection(entry, promise); promise.addListener(new FutureListener<T>() { @Override public void operationComplete(Future<T> future) throws Exception { if (future.isSuccess()) { T conn = future.getNow(); releaseConnection(entry, conn); } releaseConnection(entry); if (!future.isSuccess()) { Throwable cause = new RedisConnectionException( "Can't init enough connections amount! Only " + (minimumIdleSize - initializedConnections.get()) + " from " + minimumIdleSize + " were initialized. Server: " + entry.getClient().getAddr(), future.cause()); initPromise.tryFailure(cause); return; } int value = initializedConnections.decrementAndGet(); if (value == 0) { log.info("{} connections initialized for {}", minimumIdleSize, entry.getClient().getAddr()); if (!initPromise.trySuccess(null)) { throw new IllegalStateException(); } } else if (value > 0 && !initPromise.isDone()) { if (requests.incrementAndGet() <= minimumIdleSize) { createConnection(checkFreezed, requests, entry, initPromise, minimumIdleSize, initializedConnections); } } } }); } }); }
From source file:org.redisson.connection.pool.ConnectionPool.java
License:Apache License
private void createConnection(final ClientConnectionsEntry entry, final RPromise<T> promise) { RFuture<T> connFuture = connect(entry); connFuture.addListener(new FutureListener<T>() { @Override//w w w. j a v a 2 s . c o m public void operationComplete(Future<T> future) throws Exception { if (!future.isSuccess()) { promiseFailure(entry, promise, future.cause()); return; } T conn = future.getNow(); if (!conn.isActive()) { promiseFailure(entry, promise, conn); return; } connectedSuccessful(entry, promise, conn); } }); }
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 w w w . ja v a 2 s . 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); }
From source file:org.redisson.connection.ReplicatedConnectionManager.java
License:Apache License
private void scheduleMasterChangeCheck(final ReplicatedServersConfig cfg) { monitorFuture = GlobalEventExecutor.INSTANCE.schedule(new Runnable() { @Override//from w w w . j a v a 2 s . c o m public void run() { final URL master = currentMaster.get(); log.debug("Current master: {}", master); final AtomicInteger count = new AtomicInteger(cfg.getNodeAddresses().size()); for (final URL addr : cfg.getNodeAddresses()) { if (isShuttingDown()) { return; } RFuture<RedisConnection> connectionFuture = connect(cfg, addr); connectionFuture.addListener(new FutureListener<RedisConnection>() { @Override public void operationComplete(Future<RedisConnection> future) throws Exception { if (!future.isSuccess()) { log.error(future.cause().getMessage(), future.cause()); if (count.decrementAndGet() == 0) { scheduleMasterChangeCheck(cfg); } return; } if (isShuttingDown()) { return; } RedisConnection connection = future.getNow(); RFuture<Map<String, String>> result = connection.async(RedisCommands.INFO_REPLICATION); result.addListener(new FutureListener<Map<String, String>>() { @Override public void operationComplete(Future<Map<String, String>> future) throws Exception { if (!future.isSuccess()) { log.error(future.cause().getMessage(), future.cause()); if (count.decrementAndGet() == 0) { scheduleMasterChangeCheck(cfg); } return; } Role role = Role.valueOf(future.getNow().get(ROLE_KEY)); if (Role.master.equals(role)) { if (master.equals(addr)) { log.debug("Current master {} unchanged", master); } else if (currentMaster.compareAndSet(master, addr)) { log.info("Master has changed from {} to {}", master, addr); changeMaster(singleSlotRange.getStartSlot(), addr.getHost(), addr.getPort()); } } if (count.decrementAndGet() == 0) { scheduleMasterChangeCheck(cfg); } } }); } }); } } }, cfg.getScanInterval(), TimeUnit.MILLISECONDS); }
From source file:org.redisson.connection.SentinelConnectionManager.java
License:Apache License
private RFuture<RedisPubSubConnection> registerSentinel(final SentinelServersConfig cfg, final URL addr, final MasterSlaveServersConfig c) { RedisClient client = createClient(addr.getHost(), addr.getPort(), c.getConnectTimeout(), c.getRetryInterval() * c.getRetryAttempts()); RedisClient oldClient = sentinels.putIfAbsent(addr.getHost() + ":" + addr.getPort(), client); if (oldClient != null) { return newSucceededFuture(null); }//from w w w .j a va2 s .co m RFuture<RedisPubSubConnection> pubsubFuture = client.connectPubSubAsync(); pubsubFuture.addListener(new FutureListener<RedisPubSubConnection>() { @Override public void operationComplete(Future<RedisPubSubConnection> future) throws Exception { if (!future.isSuccess()) { log.warn("Can't connect to sentinel: {}:{}", addr.getHost(), addr.getPort()); return; } RedisPubSubConnection pubsub = future.getNow(); pubsub.addListener(new BaseRedisPubSubListener() { @Override public void onMessage(String channel, Object msg) { if ("+sentinel".equals(channel)) { onSentinelAdded(cfg, (String) msg, c); } if ("+slave".equals(channel)) { onSlaveAdded(addr, (String) msg); } if ("+sdown".equals(channel)) { onNodeDown(addr, (String) msg); } if ("-sdown".equals(channel)) { onNodeUp(addr, (String) msg); } if ("+switch-master".equals(channel)) { onMasterChange(cfg, addr, (String) msg); } } @Override public boolean onStatus(PubSubType type, String channel) { if (type == PubSubType.SUBSCRIBE) { log.debug("subscribed to channel: {} from Sentinel {}:{}", channel, addr.getHost(), addr.getPort()); } return true; } }); pubsub.subscribe(StringCodec.INSTANCE, "+switch-master", "+sdown", "-sdown", "+slave", "+sentinel"); log.info("sentinel: {}:{} added", addr.getHost(), addr.getPort()); } }); return pubsubFuture; }
From source file:org.redisson.connection.SubscribesConnectionEntry.java
License:Apache License
public Future<RedisPubSubConnection> connectPubSub(MasterSlaveServersConfig config) { Future<RedisPubSubConnection> future = super.connectPubSub(config); future.addListener(new FutureListener<RedisPubSubConnection>() { @Override/*from w w w . j ava 2 s . c om*/ public void operationComplete(Future<RedisPubSubConnection> future) throws Exception { if (!future.isSuccess()) { return; } RedisPubSubConnection conn = future.getNow(); allSubscribeConnections.add(conn); } }); return future; }
From source file:org.redisson.core.RedissonMultiLock.java
License:Apache License
private void lock(final Promise<Void> promise, final long waitTime, final long leaseTime, final TimeUnit unit) throws InterruptedException { final AtomicInteger tryLockRequestsAmount = new AtomicInteger(); final Map<Future<Boolean>, RLock> tryLockFutures = new HashMap<Future<Boolean>, RLock>(locks.size()); FutureListener<Boolean> listener = new FutureListener<Boolean>() { AtomicBoolean unlock = new AtomicBoolean(); @Override//from w w w . ja v a 2 s .c o m public void operationComplete(Future<Boolean> future) throws Exception { if (!future.isSuccess()) { // unlock once if (unlock.compareAndSet(false, true)) { for (RLock lock : locks) { lock.unlockAsync(); } promise.setFailure(future.cause()); } return; } Boolean res = future.getNow(); // unlock once if (!res && unlock.compareAndSet(false, true)) { for (RLock lock : locks) { lock.unlockAsync(); } RLock lock = tryLockFutures.get(future); lock.lockAsync().addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess()) { promise.setFailure(future.cause()); return; } lock(promise, waitTime, leaseTime, unit); } }); } if (!unlock.get() && tryLockRequestsAmount.decrementAndGet() == 0) { promise.setSuccess(null); } } }; for (RLock lock : locks) { if (lock.isHeldByCurrentThread()) { continue; } tryLockRequestsAmount.incrementAndGet(); if (waitTime > 0 || leaseTime > 0) { tryLockFutures.put(lock.tryLockAsync(waitTime, leaseTime, unit), lock); } else { tryLockFutures.put(lock.tryLockAsync(), lock); } } for (Future<Boolean> future : tryLockFutures.keySet()) { future.addListener(listener); } }
From source file:org.redisson.executor.TasksService.java
License:Apache License
public RFuture<Boolean> cancelExecutionAsync(final String requestId) { final Class<?> syncInterface = RemoteExecutorService.class; String requestQueueName = getRequestQueueName(syncInterface); if (!redisson.getMap(tasksName, LongCodec.INSTANCE).containsKey(requestId)) { return RedissonPromise.newSucceededFuture(false); }//from w w w .j a va2 s .co m final RPromise<Boolean> result = new RedissonPromise<Boolean>(); RBlockingQueue<RemoteServiceRequest> requestQueue = redisson.getBlockingQueue(requestQueueName, codec); RemoteServiceRequest request = new RemoteServiceRequest(requestId); RFuture<Boolean> removeFuture = removeAsync(requestQueue, request); removeFuture.addListener(new FutureListener<Boolean>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { if (!future.isSuccess()) { result.tryFailure(future.cause()); return; } if (future.getNow()) { result.trySuccess(true); } else { String cancelRequestMapName = getCancelRequestMapName(syncInterface); RMap<String, RemoteServiceCancelRequest> canceledRequests = redisson .getMap(cancelRequestMapName, codec); canceledRequests.putAsync(requestId, new RemoteServiceCancelRequest(true, true)); canceledRequests.expireAsync(60, TimeUnit.SECONDS); String cancelResponseMapName = getCancelResponseMapName(syncInterface); final RPromise<RemoteServiceCancelResponse> response = new RedissonPromise<RemoteServiceCancelResponse>(); scheduleCheck(cancelResponseMapName, requestId, response); response.addListener(new FutureListener<RemoteServiceCancelResponse>() { @Override public void operationComplete(Future<RemoteServiceCancelResponse> future) throws Exception { if (!future.isSuccess()) { result.tryFailure(future.cause()); return; } if (response.getNow() == null) { result.trySuccess(false); return; } result.trySuccess(response.getNow().isCanceled()); } }); } } }); return result; }