Search in sources :

Example 41 with ChannelFutureListener

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

the class RedisConnection method async.

public <T, R> RFuture<R> async(long timeout, Codec encoder, RedisCommand<T> command, Object... params) {
    CompletableFuture<R> promise = new CompletableFuture<>();
    if (timeout == -1) {
        timeout = redisClient.getCommandTimeout();
    }
    if (redisClient.getEventLoopGroup().isShuttingDown()) {
        RedissonShutdownException cause = new RedissonShutdownException("Redisson is shutdown");
        return RedissonPromise.newFailedFuture(cause);
    }
    Timeout scheduledFuture = redisClient.getTimer().newTimeout(t -> {
        RedisTimeoutException ex = new RedisTimeoutException("Command execution timeout for command: " + LogHelper.toString(command, params) + ", Redis client: " + redisClient);
        promise.completeExceptionally(ex);
    }, timeout, TimeUnit.MILLISECONDS);
    promise.whenComplete((res, e) -> {
        scheduledFuture.cancel();
    });
    ChannelFuture writeFuture = send(new CommandData<>(promise, encoder, command, params));
    writeFuture.addListener((ChannelFutureListener) future -> {
        if (!future.isSuccess()) {
            promise.completeExceptionally(future.cause());
        }
    });
    return new CompletableFutureWrapper<>(promise);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AttributeKey(io.netty.util.AttributeKey) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) Codec(org.redisson.client.codec.Codec) CommandsQueue(org.redisson.client.handler.CommandsQueue) org.redisson.client.protocol(org.redisson.client.protocol) RedissonPromise(org.redisson.misc.RedissonPromise) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) Deque(java.util.Deque) RedissonShutdownException(org.redisson.RedissonShutdownException) CommandsQueuePubSub(org.redisson.client.handler.CommandsQueuePubSub) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) RFuture(org.redisson.api.RFuture) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Queue(java.util.Queue) LogHelper(org.redisson.misc.LogHelper) CompletableFuture(java.util.concurrent.CompletableFuture) Timeout(io.netty.util.Timeout) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) RedissonShutdownException(org.redisson.RedissonShutdownException)

Example 42 with ChannelFutureListener

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

the class RedisCommonBatchExecutor method sendCommand.

private void sendCommand(RedisConnection connection, CompletableFuture<Void> attemptPromise, List<CommandData<?, ?>> list) {
    boolean isAtomic = options.getExecutionMode() != ExecutionMode.IN_MEMORY;
    boolean isQueued = options.getExecutionMode() == ExecutionMode.REDIS_READ_ATOMIC || options.getExecutionMode() == ExecutionMode.REDIS_WRITE_ATOMIC;
    CommandData<?, ?> lastCommand = connection.getLastCommand();
    if (lastCommand != null && options.isSkipResult()) {
        writeFuture = connection.getChannel().newPromise();
        lastCommand.getPromise().whenComplete((r, e) -> {
            CommandData<?, ?> currentLastCommand = connection.getLastCommand();
            if (lastCommand != currentLastCommand && currentLastCommand != null) {
                sendCommand(connection, attemptPromise, list);
                return;
            }
            ChannelFuture wf = connection.send(new CommandsData(attemptPromise, list, options.isSkipResult(), isAtomic, isQueued, options.getSyncSlaves() > 0));
            wf.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    ((ChannelPromise) writeFuture).trySuccess(future.getNow());
                } else {
                    ((ChannelPromise) writeFuture).tryFailure(future.cause());
                }
            });
        });
        return;
    }
    writeFuture = connection.send(new CommandsData(attemptPromise, list, options.isSkipResult(), isAtomic, isQueued, options.getSyncSlaves() > 0));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RedisConnection(org.redisson.client.RedisConnection) Logger(org.slf4j.Logger) StringCodec(org.redisson.client.codec.StringCodec) ConnectionManager(org.redisson.connection.ConnectionManager) LoggerFactory(org.slf4j.LoggerFactory) CommandData(org.redisson.client.protocol.CommandData) CompletableFuture(java.util.concurrent.CompletableFuture) BatchOptions(org.redisson.api.BatchOptions) ExecutionMode(org.redisson.api.BatchOptions.ExecutionMode) Redirect(org.redisson.connection.NodeSource.Redirect) ChannelFuture(io.netty.channel.ChannelFuture) RedisCommands(org.redisson.client.protocol.RedisCommands) ArrayList(java.util.ArrayList) NodeSource(org.redisson.connection.NodeSource) List(java.util.List) ChannelPromise(io.netty.channel.ChannelPromise) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Entry(org.redisson.command.CommandBatchService.Entry) RedissonObjectBuilder(org.redisson.liveobject.core.RedissonObjectBuilder) CommandsData(org.redisson.client.protocol.CommandsData) CommandsData(org.redisson.client.protocol.CommandsData)

Example 43 with ChannelFutureListener

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

the class PublishSubscribeService method unsubscribe.

public CompletableFuture<Void> unsubscribe(PubSubType topicType, ChannelName channelName) {
    PubSubConnectionEntry entry = name2PubSubConnection.remove(createKey(channelName));
    if (entry == null || connectionManager.isShuttingDown()) {
        return CompletableFuture.completedFuture(null);
    }
    AtomicBoolean executed = new AtomicBoolean();
    CompletableFuture<Void> result = new CompletableFuture<>();
    BaseRedisPubSubListener listener = new BaseRedisPubSubListener() {

        @Override
        public boolean onStatus(PubSubType type, CharSequence channel) {
            if (type == topicType && channel.equals(channelName)) {
                executed.set(true);
                if (entry.release() == 1) {
                    MasterSlaveEntry msEntry = getEntry(channelName);
                    msEntry.returnPubSubConnection(entry.getConnection());
                }
                result.complete(null);
                return true;
            }
            return false;
        }
    };
    ChannelFuture future;
    if (topicType == PubSubType.UNSUBSCRIBE) {
        future = entry.unsubscribe(channelName, listener);
    } else {
        future = entry.punsubscribe(channelName, listener);
    }
    future.addListener((ChannelFutureListener) f -> {
        if (!f.isSuccess()) {
            return;
        }
        connectionManager.newTimeout(timeout -> {
            if (executed.get()) {
                return;
            }
            entry.getConnection().onMessage(new PubSubStatusMessage(topicType, channelName));
        }, config.getTimeout(), TimeUnit.MILLISECONDS);
    });
    return result;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) PubSubType(org.redisson.client.protocol.pubsub.PubSubType) Timeout(io.netty.util.Timeout) PubSubStatusMessage(org.redisson.client.protocol.pubsub.PubSubStatusMessage) java.util(java.util) Logger(org.slf4j.Logger) Codec(org.redisson.client.codec.Codec) ConnectionManager(org.redisson.connection.ConnectionManager) java.util.concurrent(java.util.concurrent) org.redisson.client(org.redisson.client) PubSubPatternStatusListener(org.redisson.PubSubPatternStatusListener) LoggerFactory(org.slf4j.LoggerFactory) MasterSlaveServersConfig(org.redisson.config.MasterSlaveServersConfig) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Collectors(java.util.stream.Collectors) ChannelFuture(io.netty.channel.ChannelFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelFutureListener(io.netty.channel.ChannelFutureListener) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PubSubStatusMessage(org.redisson.client.protocol.pubsub.PubSubStatusMessage) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) PubSubType(org.redisson.client.protocol.pubsub.PubSubType)

Example 44 with ChannelFutureListener

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

the class PublishSubscribeService method subscribe.

private void subscribe(Codec codec, ChannelName channelName, MasterSlaveEntry entry, CompletableFuture<PubSubConnectionEntry> promise, PubSubType type, AsyncSemaphore lock, AtomicInteger attempts, RedisPubSubListener<?>... listeners) {
    PubSubConnectionEntry connEntry = name2PubSubConnection.get(new PubSubKey(channelName, entry));
    if (connEntry != null) {
        addListeners(channelName, promise, type, lock, connEntry, listeners);
        return;
    }
    Timeout lockTimeout = connectionManager.newTimeout(timeout -> {
        promise.completeExceptionally(new RedisTimeoutException("Unable to acquire subscription lock after " + config.getTimeout() + "ms. " + "Increase 'subscriptionsPerConnection' and/or 'subscriptionConnectionPoolSize' parameters."));
    }, config.getTimeout(), TimeUnit.MILLISECONDS);
    freePubSubLock.acquire(() -> {
        if (!lockTimeout.cancel() || promise.isDone()) {
            lock.release();
            freePubSubLock.release();
            return;
        }
        MasterSlaveEntry msEntry = Optional.ofNullable(connectionManager.getEntry(entry.getClient())).orElse(entry);
        PubSubEntry freePubSubConnections = entry2PubSubConnection.getOrDefault(msEntry, new PubSubEntry());
        PubSubConnectionEntry freeEntry = freePubSubConnections.getEntries().peek();
        if (freeEntry == null) {
            freePubSubLock.release();
            CompletableFuture<RedisPubSubConnection> connectFuture = connect(codec, channelName, msEntry, promise, type, lock, listeners);
            connectionManager.newTimeout(t -> {
                if (attempts.get() == config.getRetryAttempts()) {
                    connectFuture.completeExceptionally(new RedisTimeoutException("Unable to acquire connection for subscription after " + attempts.get() + " attempts. " + "Increase 'subscriptionsPerConnection' and/or 'subscriptionConnectionPoolSize' parameters."));
                    return;
                }
                if (connectFuture.cancel(true)) {
                    subscribe(codec, channelName, entry, promise, type, lock, attempts, listeners);
                    attempts.incrementAndGet();
                }
            }, config.getRetryInterval(), TimeUnit.MILLISECONDS);
            return;
        }
        int remainFreeAmount = freeEntry.tryAcquire();
        if (remainFreeAmount == -1) {
            throw new IllegalStateException();
        }
        PubSubKey key = new PubSubKey(channelName, msEntry);
        PubSubConnectionEntry oldEntry = name2PubSubConnection.putIfAbsent(key, freeEntry);
        if (oldEntry != null) {
            freeEntry.release();
            freePubSubLock.release();
            addListeners(channelName, promise, type, lock, oldEntry, listeners);
            return;
        }
        if (remainFreeAmount == 0) {
            freePubSubConnections.getEntries().poll();
        }
        freePubSubLock.release();
        CompletableFuture<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((ChannelFutureListener) future1 -> {
            if (!future1.isSuccess()) {
                if (!promise.isDone()) {
                    subscribeFuture.cancel(false);
                }
                return;
            }
            connectionManager.newTimeout(timeout -> {
                if (subscribeFuture.completeExceptionally(new RedisTimeoutException("Subscription timeout after " + config.getTimeout() + "ms. " + "Check network and/or increase 'timeout' parameter."))) {
                    unsubscribe(channelName, type);
                }
            }, config.getTimeout(), TimeUnit.MILLISECONDS);
        });
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) PubSubType(org.redisson.client.protocol.pubsub.PubSubType) Timeout(io.netty.util.Timeout) PubSubStatusMessage(org.redisson.client.protocol.pubsub.PubSubStatusMessage) java.util(java.util) Logger(org.slf4j.Logger) Codec(org.redisson.client.codec.Codec) ConnectionManager(org.redisson.connection.ConnectionManager) java.util.concurrent(java.util.concurrent) org.redisson.client(org.redisson.client) PubSubPatternStatusListener(org.redisson.PubSubPatternStatusListener) LoggerFactory(org.slf4j.LoggerFactory) MasterSlaveServersConfig(org.redisson.config.MasterSlaveServersConfig) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Collectors(java.util.stream.Collectors) ChannelFuture(io.netty.channel.ChannelFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelFutureListener(io.netty.channel.ChannelFutureListener) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) Timeout(io.netty.util.Timeout) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry)

Example 45 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project pinpoint by naver.

the class NettyIT method writeTest.

@Test
public void writeTest() throws Exception {
    final CountDownLatch awaitLatch = new CountDownLatch(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(2);
    Bootstrap bootstrap = client(workerGroup);
    final ChannelFuture connect = bootstrap.connect(webServer.getHostname(), webServer.getListeningPort());
    connect.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                Channel channel = future.channel();
                channel.pipeline().addLast(new SimpleChannelInboundHandler() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
                        awaitLatch.countDown();
                    }
                });
                HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
                future.channel().writeAndFlush(request);
            }
        }
    });
    boolean await = awaitLatch.await(3000, TimeUnit.MILLISECONDS);
    Assert.assertTrue(await);
    final Channel channel = connect.channel();
    try {
        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();
        verifier.verifyTrace(event("NETTY", Bootstrap.class.getMethod("connect", SocketAddress.class), annotation("netty.address", webServer.getHostAndPort())));
        verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPromise.addListener(io.netty.util.concurrent.GenericFutureListener)"));
        verifier.verifyTrace(event("ASYNC", "Asynchronous Invocation"));
        verifier.verifyTrace(event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListenersNow()"));
        verifier.verifyTrace(event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListener0(io.netty.util.concurrent.Future, io.netty.util.concurrent.GenericFutureListener)"));
        verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPipeline.writeAndFlush(java.lang.Object)"));
        verifier.verifyTrace(event("NETTY_HTTP", "io.netty.handler.codec.http.HttpObjectEncoder.encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)", annotation("http.url", "/")));
    } finally {
        channel.close().sync();
        workerGroup.shutdown();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Aggregations

ChannelFutureListener (io.netty.channel.ChannelFutureListener)223 ChannelFuture (io.netty.channel.ChannelFuture)208 Channel (io.netty.channel.Channel)70 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)57 ByteBuf (io.netty.buffer.ByteBuf)49 Bootstrap (io.netty.bootstrap.Bootstrap)43 Test (org.junit.jupiter.api.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)36 IOException (java.io.IOException)35 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)33 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)31 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)31 InetSocketAddress (java.net.InetSocketAddress)27 ClosedChannelException (java.nio.channels.ClosedChannelException)25 ChannelPromise (io.netty.channel.ChannelPromise)21 Logger (org.slf4j.Logger)21 LoggerFactory (org.slf4j.LoggerFactory)21 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)20 EventLoopGroup (io.netty.channel.EventLoopGroup)18 List (java.util.List)17