Search in sources :

Example 11 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project redisson by redisson.

the class RedissonRemoteService method subscribe.

private <T> void subscribe(final Class<T> remoteInterface, final RBlockingQueue<RemoteServiceRequest> requestQueue, final ExecutorService executor) {
    RFuture<RemoteServiceRequest> take = requestQueue.takeAsync();
    take.addListener(new FutureListener<RemoteServiceRequest>() {

        @Override
        public void operationComplete(Future<RemoteServiceRequest> future) throws Exception {
            if (!future.isSuccess()) {
                if (future.cause() instanceof RedissonShutdownException) {
                    return;
                }
                log.error("Can't process the remote service request.", future.cause());
                // re-subscribe after a failed takeAsync
                subscribe(remoteInterface, requestQueue, executor);
                return;
            }
            // do not subscribe now, see
            // https://github.com/mrniko/redisson/issues/493
            // subscribe(remoteInterface, requestQueue);
            final RemoteServiceRequest request = future.getNow();
            // check the ack only if expected
            if (request.getOptions().isAckExpected() && System.currentTimeMillis() - request.getDate() > request.getOptions().getAckTimeoutInMillis()) {
                log.debug("request: {} has been skipped due to ackTimeout");
                // re-subscribe after a skipped ackTimeout
                subscribe(remoteInterface, requestQueue, executor);
                return;
            }
            final String responseName = getResponseQueueName(remoteInterface, request.getRequestId());
            // send the ack only if expected
            if (request.getOptions().isAckExpected()) {
                String ackName = getAckName(remoteInterface, request.getRequestId());
                RFuture<Boolean> ackClientsFuture = commandExecutor.evalWriteAsync(responseName, LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, "if redis.call('setnx', KEYS[1], 1) == 1 then " + "redis.call('pexpire', KEYS[1], ARGV[2]);" + "redis.call('rpush', KEYS[2], ARGV[1]);" + "redis.call('pexpire', KEYS[2], ARGV[2]);" + "return 1;" + "end;" + "return 0;", Arrays.<Object>asList(ackName, responseName), encode(new RemoteServiceAck()), request.getOptions().getAckTimeoutInMillis());
                ackClientsFuture.addListener(new FutureListener<Boolean>() {

                    @Override
                    public void operationComplete(Future<Boolean> future) throws Exception {
                        if (!future.isSuccess()) {
                            log.error("Can't send ack for request: " + request, future.cause());
                            if (future.cause() instanceof RedissonShutdownException) {
                                return;
                            }
                            // re-subscribe after a failed send (ack)
                            subscribe(remoteInterface, requestQueue, executor);
                            return;
                        }
                        if (!future.getNow()) {
                            subscribe(remoteInterface, requestQueue, executor);
                            return;
                        }
                        executeMethod(remoteInterface, requestQueue, executor, request);
                    }
                });
            } else {
                executeMethod(remoteInterface, requestQueue, executor, request);
            }
        }
    });
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) RFuture(org.redisson.api.RFuture) RemoteServiceRequest(org.redisson.remote.RemoteServiceRequest) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) RemoteServiceAck(org.redisson.remote.RemoteServiceAck)

Example 12 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project netty by netty.

the class SslHandlerTest method testCloseNotify.

private static void testCloseNotify(SslProvider provider, final long closeNotifyReadTimeout, final boolean timeout) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(provider).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        final Promise<Channel> clientPromise = group.next().newPromise();
        final Promise<Channel> serverPromise = group.next().newPromise();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                SslHandler handler = sslServerCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                handler.sslCloseFuture().addListener(new PromiseNotifier<Channel, Future<Channel>>(serverPromise));
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (!future.isSuccess()) {
                            // Something bad happened during handshake fail the promise!
                            serverPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                final AtomicBoolean closeSent = new AtomicBoolean();
                if (timeout) {
                    ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (closeSent.get()) {
                                // Drop data on the floor so we will get a timeout while waiting for the
                                // close_notify.
                                ReferenceCountUtil.release(msg);
                            } else {
                                super.channelRead(ctx, msg);
                            }
                        }
                    });
                }
                SslHandler handler = sslClientCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                handler.sslCloseFuture().addListener(new PromiseNotifier<Channel, Future<Channel>>(clientPromise));
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (future.isSuccess()) {
                            closeSent.compareAndSet(false, true);
                            future.getNow().close();
                        } else {
                            // Something bad happened during handshake fail the promise!
                            clientPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).connect(sc.localAddress()).syncUninterruptibly().channel();
        serverPromise.awaitUninterruptibly();
        clientPromise.awaitUninterruptibly();
        // Server always received the close_notify as the client triggers the close sequence.
        assertTrue(serverPromise.isSuccess());
        // Depending on if we wait for the response or not the promise will be failed or not.
        if (closeNotifyReadTimeout > 0 && !timeout) {
            assertTrue(clientPromise.isSuccess());
        } else {
            assertFalse(clientPromise.isSuccess());
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) PromiseNotifier(io.netty.util.concurrent.PromiseNotifier) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) CodecException(io.netty.handler.codec.CodecException) SSLProtocolException(javax.net.ssl.SSLProtocolException) DecoderException(io.netty.handler.codec.DecoderException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 13 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project redisson by redisson.

the class ConnectionPool method scheduleCheck.

private void scheduleCheck(final ClientConnectionsEntry entry) {
    connectionManager.getConnectionEventsHub().fireDisconnect(entry.getClient().getAddr());
    connectionManager.newTimeout(new TimerTask() {

        @Override
        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);
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) Timeout(io.netty.util.Timeout) RFuture(org.redisson.api.RFuture) RedisConnectionException(org.redisson.client.RedisConnectionException) TimerTask(io.netty.util.TimerTask) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) RedisConnection(org.redisson.client.RedisConnection)

Example 14 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project redisson by redisson.

the class CommandAsyncService method evalAllAsync.

public <T, R> RFuture<R> evalAllAsync(boolean readOnlyMode, RedisCommand<T> command, final SlotCallback<T, R> callback, String script, List<Object> keys, Object... params) {
    final RPromise<R> mainPromise = connectionManager.newPromise();
    final Set<MasterSlaveEntry> entries = connectionManager.getEntrySet();
    final AtomicInteger counter = new AtomicInteger(entries.size());
    FutureListener<T> listener = new FutureListener<T>() {

        @Override
        public void operationComplete(Future<T> future) throws Exception {
            if (!future.isSuccess()) {
                mainPromise.tryFailure(future.cause());
                return;
            }
            callback.onSlotResult(future.getNow());
            if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) {
                mainPromise.trySuccess(callback.onFinish());
            }
        }
    };
    List<Object> args = new ArrayList<Object>(2 + keys.size() + params.length);
    args.add(script);
    args.add(keys.size());
    args.addAll(keys);
    args.addAll(Arrays.asList(params));
    for (MasterSlaveEntry entry : entries) {
        RPromise<T> promise = connectionManager.newPromise();
        promise.addListener(listener);
        async(readOnlyMode, new NodeSource(entry), connectionManager.getCodec(), command, args.toArray(), promise, 0);
    }
    return mainPromise;
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ArrayList(java.util.ArrayList) NodeSource(org.redisson.connection.NodeSource) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) RFuture(org.redisson.api.RFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future)

Example 15 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project redisson by redisson.

the class CommandAsyncService method handleBlockingOperations.

private <R, V> void handleBlockingOperations(final AsyncDetails<V, R> details, final RedisConnection connection, Long popTimeout) {
    final FutureListener<Boolean> listener = new FutureListener<Boolean>() {

        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            details.getMainPromise().tryFailure(new RedissonShutdownException("Redisson is shutdown"));
        }
    };
    final AtomicBoolean canceledByScheduler = new AtomicBoolean();
    final Timeout scheduledFuture;
    if (popTimeout != 0) {
        // to handle cases when connection has been lost
        final Channel orignalChannel = connection.getChannel();
        scheduledFuture = connectionManager.newTimeout(new TimerTask() {

            @Override
            public void run(Timeout timeout) throws Exception {
                // and connection is still active
                if (orignalChannel == connection.getChannel() && connection.isActive()) {
                    return;
                }
                canceledByScheduler.set(true);
                details.getAttemptPromise().trySuccess(null);
            }
        }, popTimeout, TimeUnit.SECONDS);
    } else {
        scheduledFuture = null;
    }
    details.getMainPromise().addListener(new FutureListener<R>() {

        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (scheduledFuture != null) {
                scheduledFuture.cancel();
            }
            synchronized (listener) {
                connectionManager.getShutdownPromise().removeListener(listener);
            }
            // handling cancel operation for commands from skipTimeout collection
            if ((future.isCancelled() && details.getAttemptPromise().cancel(true)) || canceledByScheduler.get()) {
                connection.forceFastReconnectAsync();
                return;
            }
            if (future.cause() instanceof RedissonShutdownException) {
                details.getAttemptPromise().tryFailure(future.cause());
            }
        }
    });
    synchronized (listener) {
        if (!details.getMainPromise().isDone()) {
            connectionManager.getShutdownPromise().addListener(listener);
        }
    }
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Timeout(io.netty.util.Timeout) Channel(io.netty.channel.Channel) RedisAskException(org.redisson.client.RedisAskException) RedisLoadingException(org.redisson.client.RedisLoadingException) RedisTimeoutException(org.redisson.client.RedisTimeoutException) RedisException(org.redisson.client.RedisException) RedisMovedException(org.redisson.client.RedisMovedException) WriteRedisConnectionException(org.redisson.client.WriteRedisConnectionException) RedisTryAgainException(org.redisson.client.RedisTryAgainException) RedissonShutdownException(org.redisson.RedissonShutdownException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TimerTask(io.netty.util.TimerTask) RFuture(org.redisson.api.RFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) RedissonShutdownException(org.redisson.RedissonShutdownException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Aggregations

Future (io.netty.util.concurrent.Future)177 Channel (io.netty.channel.Channel)61 ChannelFuture (io.netty.channel.ChannelFuture)58 InetSocketAddress (java.net.InetSocketAddress)45 ArrayList (java.util.ArrayList)45 IOException (java.io.IOException)44 GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)42 CompletableFuture (java.util.concurrent.CompletableFuture)40 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)35 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)34 List (java.util.List)34 ChannelFutureListener (io.netty.channel.ChannelFutureListener)31 EventLoopGroup (io.netty.channel.EventLoopGroup)30 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)30 FutureListener (io.netty.util.concurrent.FutureListener)28 Logger (org.slf4j.Logger)28 LoggerFactory (org.slf4j.LoggerFactory)28 TimeUnit (java.util.concurrent.TimeUnit)27 Bootstrap (io.netty.bootstrap.Bootstrap)25 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)25