Example usage for io.netty.channel ChannelOption TCP_NODELAY

List of usage examples for io.netty.channel ChannelOption TCP_NODELAY

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption TCP_NODELAY.

Prototype

ChannelOption TCP_NODELAY

To view the source code for io.netty.channel ChannelOption TCP_NODELAY.

Click Source Link

Usage

From source file:org.apache.hadoop.hbase.ipc.AsyncRpcClient.java

License:Apache License

/**
 * Constructor for tests//w  w  w  .j  a  va  2  s .  co m
 *
 * @param configuration      to HBase
 * @param clusterId          for the cluster
 * @param localAddress       local address to connect to
 * @param channelInitializer for custom channel handlers
 */
@VisibleForTesting
AsyncRpcClient(Configuration configuration, String clusterId, SocketAddress localAddress,
        ChannelInitializer<SocketChannel> channelInitializer) {
    super(configuration, clusterId, localAddress);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Starting async Hbase RPC client");
    }

    Pair<EventLoopGroup, Class<? extends Channel>> eventLoopGroupAndChannelClass;
    this.useGlobalEventLoopGroup = conf.getBoolean(USE_GLOBAL_EVENT_LOOP_GROUP, true);
    if (useGlobalEventLoopGroup) {
        eventLoopGroupAndChannelClass = getGlobalEventLoopGroup(configuration);
    } else {
        eventLoopGroupAndChannelClass = createEventLoopGroup(configuration);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Use " + (useGlobalEventLoopGroup ? "global" : "individual") + " event loop group "
                + eventLoopGroupAndChannelClass.getFirst().getClass().getSimpleName());
    }

    this.connections = new PoolMap<>(getPoolType(configuration), getPoolSize(configuration));
    this.failedServers = new FailedServers(configuration);

    int operationTimeout = configuration.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
            HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);

    // Configure the default bootstrap.
    this.bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroupAndChannelClass.getFirst()).channel(eventLoopGroupAndChannelClass.getSecond())
            .option(ChannelOption.TCP_NODELAY, tcpNoDelay).option(ChannelOption.SO_KEEPALIVE, tcpKeepAlive)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, operationTimeout);
    if (channelInitializer == null) {
        channelInitializer = DEFAULT_CHANNEL_INITIALIZER;
    }
    bootstrap.handler(channelInitializer);
    if (localAddress != null) {
        bootstrap.localAddress(localAddress);
    }
}

From source file:org.apache.hadoop.hbase.ipc.NettyRpcConnection.java

License:Apache License

private void connect() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting to " + remoteId.address);
    }//from   w  w  w. j  a v  a 2 s. co m

    this.channel = new Bootstrap().group(rpcClient.group).channel(rpcClient.channelClass)
            .option(ChannelOption.TCP_NODELAY, rpcClient.isTcpNoDelay())
            .option(ChannelOption.SO_KEEPALIVE, rpcClient.tcpKeepAlive)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, rpcClient.connectTO)
            .handler(new BufferCallBeforeInitHandler()).localAddress(rpcClient.localAddr)
            .remoteAddress(remoteId.address).connect().addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    Channel ch = future.channel();
                    if (!future.isSuccess()) {
                        failInit(ch, toIOE(future.cause()));
                        rpcClient.failedServers.addToFailedServers(remoteId.address);
                        return;
                    }
                    ch.writeAndFlush(connectionHeaderPreamble.retainedDuplicate());
                    if (useSasl) {
                        saslNegotiate(ch);
                    } else {
                        // send the connection header to server
                        ch.write(connectionHeaderWithLength.retainedDuplicate());
                        established(ch);
                    }
                }
            }).channel();
}

From source file:org.apache.hadoop.hbase.ipc.NettyRpcServer.java

License:Apache License

public NettyRpcServer(final Server server, final String name, final List<BlockingServiceAndInterface> services,
        final InetSocketAddress bindAddress, Configuration conf, RpcScheduler scheduler) throws IOException {
    super(server, name, services, bindAddress, conf, scheduler);
    this.bindAddress = bindAddress;
    boolean useEpoll = useEpoll(conf);
    int workerCount = conf.getInt("hbase.netty.rpc.server.worker.count",
            Runtime.getRuntime().availableProcessors() / 4);
    EventLoopGroup bossGroup = null;//from  w w w.  java  2s.c o m
    EventLoopGroup workerGroup = null;
    if (useEpoll) {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup(workerCount);
    } else {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(workerCount);
    }
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    if (useEpoll) {
        bootstrap.channel(EpollServerSocketChannel.class);
    } else {
        bootstrap.channel(NioServerSocketChannel.class);
    }
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childHandler(new Initializer(maxRequestSize));

    try {
        serverChannel = bootstrap.bind(this.bindAddress).sync().channel();
        LOG.info("NettyRpcServer bind to address=" + serverChannel.localAddress()
                + ", hbase.netty.rpc.server.worker.count=" + workerCount + ", useEpoll=" + useEpoll);
        allChannels.add(serverChannel);
    } catch (InterruptedException e) {
        throw new InterruptedIOException(e.getMessage());
    }
    initReconfigurable(conf);
    this.scheduler.init(new RpcSchedulerContext(this));
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.client.StandbyClient.java

License:Apache License

public void run() {
    if (!isRunning()) {
        // manually stopped
        return;/*  www  .  j  a  v  a2s  .c  om*/
    }

    Bootstrap b;
    synchronized (this.sync) {
        if (this.active) {
            return;
        }
        state = STATUS_STARTING;
        handler = new StandbyClientHandler(this.store, observer, running, readTimeoutMs, autoClean);
        group = new NioEventLoopGroup();

        b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, readTimeoutMs);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_REUSEADDR, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslContext != null) {
                    p.addLast(sslContext.newHandler(ch.alloc()));
                }
                p.addLast("readTimeoutHandler", new ReadTimeoutHandler(readTimeoutMs, TimeUnit.MILLISECONDS));
                p.addLast(new StringEncoder(CharsetUtil.UTF_8));
                p.addLast(new SnappyFramedDecoder(true));
                p.addLast(new RecordIdDecoder(store));
                p.addLast(handler);
            }
        });
        state = STATUS_RUNNING;
        this.active = true;
    }

    try {
        long startTimestamp = System.currentTimeMillis();
        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
        this.failedRequests = 0;
        this.syncStartTimestamp = startTimestamp;
        this.syncEndTimestamp = System.currentTimeMillis();
        this.lastSuccessfulRequest = syncEndTimestamp / 1000;
    } catch (Exception e) {
        this.failedRequests++;
        log.error("Failed synchronizing state.", e);
    } finally {
        synchronized (this.sync) {
            this.active = false;
            shutdownNetty();
        }
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.server.StandbyServer.java

License:Apache License

public StandbyServer(int port, final SegmentStore store, String[] allowedClientIPRanges, boolean secure)
        throws CertificateException, SSLException {
    this.port = port;

    if (secure) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    }// ww  w.  ja  v  a  2s  .co  m

    observer = new CommunicationObserver("primary");
    handler = new StandbyServerHandler(store, observer, allowedClientIPRanges);
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();

    final MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
    try {
        jmxServer.registerMBean(new StandardMBean(this, StandbyStatusMBean.class),
                new ObjectName(this.getMBeanName()));
    } catch (Exception e) {
        log.error("can't register standby status mbean", e);
    }

    b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.channel(NioServerSocketChannel.class);

    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.childOption(ChannelOption.TCP_NODELAY, true);
    b.childOption(ChannelOption.SO_REUSEADDR, true);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslContext != null) {
                p.addLast(sslContext.newHandler(ch.alloc()));
            }
            p.addLast(new LineBasedFrameDecoder(8192));
            p.addLast(new StringDecoder(CharsetUtil.UTF_8));
            p.addLast(new SnappyFramedEncoder());
            p.addLast(new RecordIdEncoder());
            p.addLast(new SegmentEncoder());
            p.addLast(new BlobEncoder());
            p.addLast(handler);
        }
    });
}

From source file:org.apache.pulsar.proxy.server.ProxyService.java

License:Apache License

public void start() throws Exception {
    if (!isBlank(proxyConfig.getZookeeperServers()) && !isBlank(proxyConfig.getConfigurationStoreServers())) {
        discoveryProvider = new BrokerDiscoveryProvider(this.proxyConfig, getZooKeeperClientFactory());
        this.configurationCacheService = new ConfigurationCacheService(discoveryProvider.globalZkCache);
        authorizationService = new AuthorizationService(PulsarConfigurationLoader.convertFrom(proxyConfig),
                configurationCacheService);
    }/*from   w  w  w  .j  a va 2 s .c  o m*/

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.group(acceptorGroup, workerGroup);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024));

    bootstrap.channel(EventLoopUtil.getServerSocketChannelClass(workerGroup));
    EventLoopUtil.enableTriggeredMode(bootstrap);

    bootstrap.childHandler(new ServiceChannelInitializer(this, proxyConfig, false));
    // Bind and start to accept incoming connections.
    if (proxyConfig.getServicePort().isPresent()) {
        try {
            bootstrap.bind(proxyConfig.getServicePort().get()).sync();
            LOG.info("Started Pulsar Proxy at {}", serviceUrl);
        } catch (Exception e) {
            throw new IOException("Failed to bind Pulsar Proxy on port " + proxyConfig.getServicePort().get(),
                    e);
        }
    }
    LOG.info("Started Pulsar Proxy at {}", serviceUrl);

    if (proxyConfig.getServicePortTls().isPresent()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new ServiceChannelInitializer(this, proxyConfig, true));
        tlsBootstrap.bind(proxyConfig.getServicePortTls().get()).sync();
        LOG.info("Started Pulsar TLS Proxy on port {}", proxyConfig.getServicePortTls().get());
    }
}

From source file:org.apache.qpid.jms.transports.netty.NettyTcpTransport.java

License:Apache License

private void configureNetty(Bootstrap bootstrap, TransportOptions options) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }//from   w  w  w . j av a  2  s  .c  o  m

    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }

    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
}

From source file:org.apache.rocketmq.remoting.netty.NettyRemotingClient.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyClientConfig.getClientWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*  ww w.  ja v a  2 s  . c om*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)//
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(),
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),
                            new NettyConnectManageHandler(), new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                NettyRemotingClient.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }
}

From source file:org.apache.rocketmq.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyServerConfig.getServerWorkerThreads(),
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*from ww w .  j av a  2s  .c o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = this.serverBootstrap
            .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
            .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
            .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(),
                            new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),
                            new NettyConnetManageHandler(), new NettyServerHandler());
                }
            });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:org.apache.spark.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException, InterruptedException {
    logger.debug("Creating new connection to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    if (conf.receiveBuf() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, conf.receiveBuf());
    }/*from   w w  w  . jav  a  2  s. c  om*/

    if (conf.sendBuf() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, conf.sendBuf());
    }

    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.await(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}