Search in sources :

Example 36 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project x-pipe by ctripcorp.

the class DefaultNettyClient method sendRequest.

@Override
public void sendRequest(ByteBuf byteBuf, final ByteBufReceiver byteBufReceiver) {
    logger.debug("[sendRequest][begin]{}, {}", byteBufReceiver, this);
    DefaultChannelPromise future = new DefaultChannelPromise(channel);
    future.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                logger.debug("[operationComplete][add receiver]{}, {}", byteBufReceiver, this);
                receivers.offer(byteBufReceiver);
            } else {
                logger.error("[sendRequest][fail]" + channel, future.cause());
            }
        }
    });
    logger.debug("[sendRequest][ end ]{}, {}", byteBufReceiver, this);
    channel.writeAndFlush(byteBuf, future);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 37 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project x-pipe by ctripcorp.

the class DefaultRedisMasterReplication method doConnect.

@Override
protected void doConnect(Bootstrap b) {
    redisMaster.setMasterState(MASTER_STATE.REDIS_REPL_CONNECTING);
    tryConnect(b).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                logger.error("[operationComplete][fail connect with master]" + redisMaster, future.cause());
                scheduled.schedule(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            connectWithMaster();
                        } catch (Throwable th) {
                            logger.error("[run][connectUntilConnected]" + DefaultRedisMasterReplication.this, th);
                        }
                    }
                }, masterConnectRetryDelaySeconds, TimeUnit.SECONDS);
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener) IOException(java.io.IOException)

Example 38 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project x-pipe by ctripcorp.

the class DefaultCommandStore method addCommandsListener.

@Override
public void addCommandsListener(long offset, final CommandsListener listener) throws IOException {
    makeSureOpen();
    logger.info("[addCommandsListener][begin] from offset {}, {}", offset, listener);
    CommandReader cmdReader = null;
    try {
        cmdReader = beginRead(offset);
    } finally {
        // ensure beforeCommand() is always called
        listener.beforeCommand();
    }
    logger.info("[addCommandsListener] from offset {}, {}", offset, cmdReader);
    try {
        while (listener.isOpen() && !Thread.currentThread().isInterrupted()) {
            final ReferenceFileRegion referenceFileRegion = cmdReader.read();
            logger.debug("[addCommandsListener] {}", referenceFileRegion);
            if (delayTraceLogger.isDebugEnabled()) {
                delayTraceLogger.debug("[write][begin]{}, {}", listener, referenceFileRegion.getTotalPos());
            }
            commandStoreDelay.beginSend(listener, referenceFileRegion.getTotalPos());
            ChannelFuture future = listener.onCommand(referenceFileRegion);
            if (future != null) {
                future.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        commandStoreDelay.flushSucceed(listener, referenceFileRegion.getTotalPos());
                        if (logger.isDebugEnabled()) {
                            delayTraceLogger.debug("[write][ end ]{}, {}", listener, referenceFileRegion.getTotalPos());
                        }
                    }
                });
            }
            if (referenceFileRegion.count() <= 0) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    } catch (Throwable th) {
        logger.error("[readCommands][exit]" + listener, th);
    } finally {
        cmdReader.close();
    }
    logger.info("[addCommandsListener][end] from offset {}, {}", offset, listener);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) CommandReader(com.ctrip.xpipe.redis.core.store.CommandReader) ChannelFutureListener(io.netty.channel.ChannelFutureListener) IOException(java.io.IOException) ReferenceFileRegion(com.ctrip.xpipe.netty.filechannel.ReferenceFileRegion)

Example 39 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project component-runtime by Talend.

the class HandlerImpl method start.

public synchronized HandlerImpl<T> start() {
    if (instance != null) {
        throw new IllegalStateException("Instance already started");
    }
    if (handler.getPort() <= 0) {
        handler.setPort(newRandomPort());
    }
    final CountDownLatch startingPistol = new CountDownLatch(1);
    instance = new Thread(() -> {
        // todo: config
        final EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("talend-api-boss"));
        final EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("talend-api-worker"));
        try {
            final ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_REUSEADDR, true).group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ProxyInitializer(handler)).bind("localhost", handler.getPort()).sync().addListener((ChannelFutureListener) f -> {
                if (f.isSuccess()) {
                    shutdown = () -> {
                        bossGroup.shutdownGracefully();
                        workerGroup.shutdownGracefully();
                    };
                } else {
                    log.error("Can't start API server");
                }
                startingPistol.countDown();
            }).channel().closeFuture().sync();
        } catch (final InterruptedException e) {
            Thread.interrupted();
            close();
        }
    }) {

        {
            setName("Talend-API-monitor_" + HandlerImpl.this.getClass().getSimpleName() + "_" + HandlerImpl.this.hashCode());
        }
    };
    log.info("Starting Talend API server on port {}", handler.getPort());
    instance.start();
    try {
        if (!startingPistol.await(Integer.getInteger("talend.junit.http.starting.timeout", 60), SECONDS)) {
            log.warn("API server took more than the expected timeout to start, you can tune it " + "setting talend.junit.http.starting.timeout system property");
        }
    } catch (final InterruptedException e) {
        Thread.interrupted();
        log.warn(e.getMessage());
    }
    if (shutdown != null && handler.isGlobalProxyConfiguration()) {
        final String pt = Integer.toString(handler.getPort());
        Stream.of("", "s").forEach(s -> {
            shutdown = decorate(setProperty("http" + s + ".proxyHost", "localhost"), shutdown);
            shutdown = decorate(setProperty("http" + s + ".proxyPort", pt), shutdown);
            shutdown = decorate(setProperty("http" + s + ".nonProxyHosts", "local|*.local"), shutdown);
        });
        if (handler.getSslContext() != null) {
            try {
                final SSLContext defaultSslContext = SSLContext.getDefault();
                final HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
                shutdown = decorate(() -> SSLContext.setDefault(defaultSslContext), shutdown);
                shutdown = decorate(() -> {
                    HttpsURLConnection.setDefaultSSLSocketFactory(defaultSslContext.getSocketFactory());
                    HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
                }, shutdown);
                SSLContext.setDefault(handler.getSslContext());
                HttpsURLConnection.setDefaultSSLSocketFactory(handler.getSslContext().getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier((host, sslSession) -> true);
            } catch (final NoSuchAlgorithmException e) {
                throw new IllegalStateException(e);
            }
        }
        log.info("Configured the JVM to use the {} API proxy localhost:{}", handler.getSslContext() != null ? "SSL" : "plain", handler.getPort());
    }
    return this;
}
Also used : HttpsURLConnection(javax.net.ssl.HttpsURLConnection) SSLContext(javax.net.ssl.SSLContext) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ChannelOption(io.netty.channel.ChannelOption) Optional.ofNullable(java.util.Optional.ofNullable) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) IOException(java.io.IOException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) HttpApiHandler(org.talend.sdk.component.junit.http.api.HttpApiHandler) ServerSocket(java.net.ServerSocket) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HostnameVerifier(javax.net.ssl.HostnameVerifier) AllArgsConstructor(lombok.AllArgsConstructor) SECONDS(java.util.concurrent.TimeUnit.SECONDS) ExecutorService(java.util.concurrent.ExecutorService) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CountDownLatch(java.util.concurrent.CountDownLatch) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HostnameVerifier(javax.net.ssl.HostnameVerifier) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 40 with ChannelFutureListener

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

the class ConnectionWatchdog method reattachBlockingQueue.

private void reattachBlockingQueue(RedisConnection connection, CommandData<?, ?> currentCommand) {
    if (currentCommand == null || !currentCommand.isBlockingCommand() || currentCommand.getPromise().isDone()) {
        return;
    }
    ChannelFuture future = connection.send(currentCommand);
    future.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                log.error("Can't reconnect blocking queue by command: {} using connection: {}", currentCommand, connection);
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

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