Search in sources :

Example 81 with ChannelFuture

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture in project flink by apache.

the class HttpTestClient method sendRequest.

/**
	 * Sends a request to to the server.
	 *
	 * <pre>
	 * HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/overview");
	 * request.headers().set(HttpHeaders.Names.HOST, host);
	 * request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
	 *
	 * sendRequest(request);
	 * </pre>
	 *
	 * @param request The {@link HttpRequest} to send to the server
	 */
public void sendRequest(HttpRequest request, FiniteDuration timeout) throws InterruptedException, TimeoutException {
    LOG.debug("Writing {}.", request);
    // Make the connection attempt.
    ChannelFuture connect = bootstrap.connect(host, port);
    Channel channel;
    if (connect.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
        channel = connect.channel();
    } else {
        throw new TimeoutException("Connection failed");
    }
    channel.writeAndFlush(request);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) TimeoutException(java.util.concurrent.TimeoutException)

Example 82 with ChannelFuture

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture in project redisson by redisson.

the class CommandBatchService method execute.

private void execute(final Entry entry, final NodeSource source, final RPromise<Void> mainPromise, final AtomicInteger slots, final int attempt, final boolean noResult) {
    if (mainPromise.isCancelled()) {
        return;
    }
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.tryFailure(new IllegalStateException("Redisson is shutdown"));
        return;
    }
    final RPromise<Void> attemptPromise = connectionManager.newPromise();
    final AsyncDetails details = new AsyncDetails();
    final RFuture<RedisConnection> connectionFuture;
    if (entry.isReadOnlyMode()) {
        connectionFuture = connectionManager.connectionReadOp(source, null);
    } else {
        connectionFuture = connectionManager.connectionWriteOp(source, null);
    }
    final TimerTask retryTimerTask = new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (connectionFuture.cancel(false)) {
                connectionManager.getShutdownLatch().release();
            } else {
                if (connectionFuture.isSuccess()) {
                    ChannelFuture writeFuture = details.getWriteFuture();
                    if (writeFuture != null && !writeFuture.cancel(false) && writeFuture.isSuccess()) {
                        return;
                    }
                }
            }
            if (mainPromise.isCancelled()) {
                attemptPromise.cancel(false);
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                if (details.getException() == null) {
                    details.setException(new RedisTimeoutException("Batch command execution timeout"));
                }
                attemptPromise.tryFailure(details.getException());
                return;
            }
            if (!attemptPromise.cancel(false)) {
                return;
            }
            int count = attempt + 1;
            execute(entry, source, mainPromise, slots, count, noResult);
        }
    };
    Timeout timeout = connectionManager.newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    details.setTimeout(timeout);
    connectionFuture.addListener(new FutureListener<RedisConnection>() {

        @Override
        public void operationComplete(Future<RedisConnection> connFuture) throws Exception {
            checkConnectionFuture(entry, source, mainPromise, attemptPromise, details, connectionFuture, noResult);
        }
    });
    attemptPromise.addListener(new FutureListener<Void>() {

        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            details.getTimeout().cancel();
            if (future.isCancelled()) {
                return;
            }
            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                entry.clearErrors();
                execute(entry, new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.MOVED), mainPromise, slots, attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisAskException) {
                RedisAskException ex = (RedisAskException) future.cause();
                entry.clearErrors();
                execute(entry, new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.ASK), mainPromise, slots, attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisLoadingException) {
                entry.clearErrors();
                execute(entry, source, mainPromise, slots, attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisTryAgainException) {
                entry.clearErrors();
                connectionManager.newTimeout(new TimerTask() {

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        execute(entry, source, mainPromise, slots, attempt, noResult);
                    }
                }, 1, TimeUnit.SECONDS);
                return;
            }
            if (future.isSuccess()) {
                if (slots.decrementAndGet() == 0) {
                    mainPromise.trySuccess(future.getNow());
                }
            } else {
                mainPromise.tryFailure(future.cause());
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RedisMovedException(org.redisson.client.RedisMovedException) RedisTryAgainException(org.redisson.client.RedisTryAgainException) Timeout(io.netty.util.Timeout) RedisLoadingException(org.redisson.client.RedisLoadingException) RedisMovedException(org.redisson.client.RedisMovedException) RedisAskException(org.redisson.client.RedisAskException) WriteRedisConnectionException(org.redisson.client.WriteRedisConnectionException) RedisLoadingException(org.redisson.client.RedisLoadingException) RedisTryAgainException(org.redisson.client.RedisTryAgainException) RedisTimeoutException(org.redisson.client.RedisTimeoutException) NodeSource(org.redisson.connection.NodeSource) TimerTask(io.netty.util.TimerTask) RedisTimeoutException(org.redisson.client.RedisTimeoutException) RedisAskException(org.redisson.client.RedisAskException) RedisConnection(org.redisson.client.RedisConnection)

Example 83 with ChannelFuture

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture in project redisson by redisson.

the class CommandAsyncService method checkWriteFuture.

private <V, R> void checkWriteFuture(final AsyncDetails<V, R> details, final RedisConnection connection) {
    ChannelFuture future = details.getWriteFuture();
    if (details.getAttemptPromise().isDone() || future.isCancelled()) {
        return;
    }
    if (!future.isSuccess()) {
        details.setException(new WriteRedisConnectionException("Can't write command: " + details.getCommand() + ", params: " + LogHelper.toString(details.getParams()) + " to channel: " + future.channel(), future.cause()));
        return;
    }
    details.getTimeout().cancel();
    long timeoutTime = connectionManager.getConfig().getTimeout();
    if (RedisCommands.BLOCKING_COMMANDS.contains(details.getCommand().getName())) {
        Long popTimeout = Long.valueOf(details.getParams()[details.getParams().length - 1].toString());
        handleBlockingOperations(details, connection, popTimeout);
        if (popTimeout == 0) {
            return;
        }
        timeoutTime += popTimeout * 1000;
        // add 1 second due to issue https://github.com/antirez/redis/issues/874
        timeoutTime += 1000;
    }
    final long timeoutAmount = timeoutTime;
    TimerTask timeoutTask = new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            details.getAttemptPromise().tryFailure(new RedisTimeoutException("Redis server response timeout (" + timeoutAmount + " ms) occured for command: " + details.getCommand() + " with params: " + LogHelper.toString(details.getParams()) + " channel: " + connection.getChannel()));
        }
    };
    Timeout timeout = connectionManager.newTimeout(timeoutTask, timeoutTime, TimeUnit.MILLISECONDS);
    details.setTimeout(timeout);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) WriteRedisConnectionException(org.redisson.client.WriteRedisConnectionException) TimerTask(io.netty.util.TimerTask) RedisTimeoutException(org.redisson.client.RedisTimeoutException) Timeout(io.netty.util.Timeout)

Example 84 with ChannelFuture

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture in project redisson by redisson.

the class MasterSlaveEntry method slaveDown.

private boolean slaveDown(ClientConnectionsEntry entry, boolean temporaryDown) {
    // add master as slave if no more slaves available
    if (config.getReadMode() == ReadMode.SLAVE && slaveBalancer.getAvailableClients() == 0) {
        InetSocketAddress addr = masterEntry.getClient().getAddr();
        if (slaveUp(addr.getHostName(), addr.getPort(), FreezeReason.SYSTEM)) {
            log.info("master {}:{} used as slave", addr.getHostName(), addr.getPort());
        }
    }
    // close all connections
    while (true) {
        final RedisConnection connection = entry.pollConnection();
        if (connection == null) {
            break;
        }
        connection.closeAsync().addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                reattachBlockingQueue(connection);
            }
        });
    }
    // close all pub/sub connections
    while (true) {
        RedisPubSubConnection connection = entry.pollSubscribeConnection();
        if (connection == null) {
            break;
        }
        connection.closeAsync();
    }
    for (RedisPubSubConnection connection : entry.getAllSubscribeConnections()) {
        reattachPubSub(connection, temporaryDown);
    }
    entry.getAllSubscribeConnections().clear();
    return true;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RedisPubSubConnection(org.redisson.client.RedisPubSubConnection) InetSocketAddress(java.net.InetSocketAddress) ChannelFutureListener(io.netty.channel.ChannelFutureListener) RedisConnection(org.redisson.client.RedisConnection)

Example 85 with ChannelFuture

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture in project redisson by redisson.

the class RedisClient method connectPubSubAsync.

public RFuture<RedisPubSubConnection> connectPubSubAsync() {
    final RPromise<RedisPubSubConnection> f = new RedissonPromise<RedisPubSubConnection>();
    ChannelFuture channelFuture = bootstrap.connect();
    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                final RedisPubSubConnection c = new RedisPubSubConnection(RedisClient.this, future.channel());
                bootstrap.group().execute(new Runnable() {

                    public void run() {
                        if (!f.trySuccess(c)) {
                            c.closeAsync();
                        }
                    }
                });
            } else {
                bootstrap.group().execute(new Runnable() {

                    public void run() {
                        f.tryFailure(future.cause());
                    }
                });
            }
        }
    });
    return f;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RedissonPromise(org.redisson.misc.RedissonPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Aggregations

ChannelFuture (io.netty.channel.ChannelFuture)936 Channel (io.netty.channel.Channel)271 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)246 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)239 Bootstrap (io.netty.bootstrap.Bootstrap)219 InetSocketAddress (java.net.InetSocketAddress)214 ChannelFutureListener (io.netty.channel.ChannelFutureListener)206 Test (org.junit.Test)195 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)194 ByteBuf (io.netty.buffer.ByteBuf)192 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)178 EventLoopGroup (io.netty.channel.EventLoopGroup)167 IOException (java.io.IOException)155 ChannelPipeline (io.netty.channel.ChannelPipeline)151 SocketChannel (io.netty.channel.socket.SocketChannel)118 ArrayList (java.util.ArrayList)118 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)116 ChannelInitializer (io.netty.channel.ChannelInitializer)115 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)112 AtomicReference (java.util.concurrent.atomic.AtomicReference)111