Example usage for io.netty.channel ChannelOption ALLOCATOR

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

Introduction

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

Prototype

ChannelOption ALLOCATOR

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

Click Source Link

Usage

From source file:NettyHttpListner.java

License:Apache License

public void start() {

    System.out.println("Starting the server...");
    System.out.println("Starting Inbound Http Listner on Port " + this.port);

    // Configure SSL.
    SslContext sslCtx = null;/*ww w.  j a  v  a  2  s .c o m*/
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SSLException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize);
    //        bossGroup = new NioEventLoopGroup(bossGroupSize);
    //        workerGroup = new NioEventLoopGroup(workerGroupSize);

    try {
        ServerBootstrap b = new ServerBootstrap();

        //            b.commonEventLoopGroup(bossGroup, workerGroup)
        b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                        new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx))
                .childOption(ChannelOption.AUTO_READ, false);

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

        b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_SNDBUF, 1048576);

        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        Channel ch = null;
        try {
            ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("Inbound Listner Started");
        } catch (InterruptedException e) {
            System.out.println("Exception caught");
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx/*  w ww. j  a v a2s . c  om*/
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

From source file:alluxio.client.netty.NettyClient.java

License:Apache License

/**
 * Creates and returns a new Netty client bootstrap for clients to connect to remote servers.
 *
 * @param handler the handler that should be added to new channel pipelines
 * @return the new client {@link Bootstrap}
 *///  w  w  w. j  av a 2 s.com
public static Bootstrap createClientBootstrap(final ClientHandler handler) {
    final Bootstrap boot = new Bootstrap();

    boot.group(WORKER_GROUP).channel(CLIENT_CHANNEL_CLASS);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    boot.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(RPCMessage.createFrameDecoder());
            pipeline.addLast(ENCODER);
            pipeline.addLast(DECODER);
            pipeline.addLast(handler);
        }
    });

    return boot;
}

From source file:alluxio.network.netty.NettyClient.java

License:Apache License

/**
 * Creates and returns a new Netty client bootstrap for clients to connect to remote servers.
 *
 * @param address the socket address/*w ww  .j  av a2  s .co m*/
 * @return the new client {@link Bootstrap}
 */
public static Bootstrap createClientBootstrap(SocketAddress address) {
    final Bootstrap boot = new Bootstrap();

    boot.group(WORKER_GROUP).channel(
            NettyUtils.getClientChannelClass(NettyUtils.CHANNEL_TYPE, !(address instanceof InetSocketAddress)));
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    if (NettyUtils.CHANNEL_TYPE == ChannelType.EPOLL) {
        boot.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    }

    // After 10 missed heartbeat attempts and no write activity, the server will close the channel.
    final long timeoutMs = Configuration.getMs(PropertyKey.NETWORK_NETTY_HEARTBEAT_TIMEOUT_MS);
    final long heartbeatPeriodMs = Math.max(timeoutMs / 10, 1);
    boot.handler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(RPCMessage.createFrameDecoder());
            pipeline.addLast(ENCODER);
            pipeline.addLast(DECODER);
            pipeline.addLast(new IdleStateHandler(0, heartbeatPeriodMs, 0, TimeUnit.MILLISECONDS));
            pipeline.addLast(new IdleWriteHandler());
        }
    });

    return boot;
}

From source file:alluxio.worker.grpc.GrpcDataServer.java

License:Apache License

private GrpcServerBuilder createServerBuilder(String hostName, SocketAddress bindAddress, ChannelType type) {
    GrpcServerBuilder builder = GrpcServerBuilder.forAddress(hostName, bindAddress,
            ServerConfiguration.global(), ServerUserState.global());
    int bossThreadCount = ServerConfiguration.getInt(PropertyKey.WORKER_NETWORK_NETTY_BOSS_THREADS);

    // If number of worker threads is 0, Netty creates (#processors * 2) threads by default.
    int workerThreadCount = ServerConfiguration.getInt(PropertyKey.WORKER_NETWORK_NETTY_WORKER_THREADS);
    String dataServerEventLoopNamePrefix = "data-server-"
            + ((mSocketAddress instanceof DomainSocketAddress) ? "domain-socket" : "tcp-socket");
    mBossGroup = NettyUtils.createEventLoop(type, bossThreadCount, dataServerEventLoopNamePrefix + "-boss-%d",
            true);//from   w ww  .  j  av a 2 s.co m
    mWorkerGroup = NettyUtils.createEventLoop(type, workerThreadCount,
            dataServerEventLoopNamePrefix + "-worker-%d", true);
    Class<? extends ServerChannel> socketChannelClass = NettyUtils
            .getServerChannelClass(mSocketAddress instanceof DomainSocketAddress, ServerConfiguration.global());
    if (type == ChannelType.EPOLL) {
        builder.withChildOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    }
    return builder.bossEventLoopGroup(mBossGroup).workerEventLoopGroup(mWorkerGroup)
            .channelType(socketChannelClass)
            .withChildOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            // set write buffer
            // this is the default, but its recommended to set it in case of change in future netty.
            .withChildOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK,
                    (int) ServerConfiguration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_HIGH))
            .withChildOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK,
                    (int) ServerConfiguration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_LOW));
}

From source file:alluxio.worker.netty.NettyDataServer.java

License:Apache License

private ServerBootstrap createBootstrap() {
    final ServerBootstrap boot = createBootstrapOfType(
            Configuration.getEnum(PropertyKey.WORKER_NETWORK_NETTY_CHANNEL, ChannelType.class));

    // use pooled buffers
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // set write buffer
    // this is the default, but its recommended to set it in case of change in future netty.
    boot.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK,
            (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_HIGH));
    boot.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK,
            (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_LOW));

    // more buffer settings on Netty socket option, one can tune them by specifying
    // properties, e.g.:
    // alluxio.worker.network.netty.backlog=50
    // alluxio.worker.network.netty.buffer.send=64KB
    // alluxio.worker.network.netty.buffer.receive=64KB
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BACKLOG)) {
        boot.option(ChannelOption.SO_BACKLOG, Configuration.getInt(PropertyKey.WORKER_NETWORK_NETTY_BACKLOG));
    }/*from  w  w w  . j  a v  a2  s  .  c o m*/
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_SEND)) {
        boot.option(ChannelOption.SO_SNDBUF,
                (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_SEND));
    }
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_RECEIVE)) {
        boot.option(ChannelOption.SO_RCVBUF,
                (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_RECEIVE));
    }
    return boot;
}

From source file:c5db.client.C5NettyConnectionManager.java

License:Apache License

public C5NettyConnectionManager() {
    bootstrap.group(group);//from ww w . j a v  a  2 s . c om
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    try {
        uri = new URI("ws://0.0.0.0:8080/websocket");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

}

From source file:c5db.regionserver.RegionServerService.java

License:Apache License

public RegionServerService(EventLoopGroup acceptGroup, EventLoopGroup workerGroup, int port, C5Server server) {
    this.acceptGroup = acceptGroup;
    this.workerGroup = workerGroup;
    this.port = port;
    this.server = server;
    this.fiber = server.getFiberSupplier().getNewFiber(this::notifyFailed);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}

From source file:cn.wcl.test.netty.server.netty.NettyHttpServer.java

License:Apache License

private void init() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* ww  w  .j  a  v  a2 s .  c o m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        b.childHandler(new HttpUploadServerInitializer(sslCtx, applicationContext, needlogin));

        Channel ch = b.bind(port).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + port + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:code.google.nfs.rpc.netty.client.NettyClientFactory.java

License:Apache License

protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
        throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
    if (connectTimeout < 1000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    } else {//from   w w w  .jav a 2s.  co m
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    }
    final NettyClientHandler handler = new NettyClientHandler(this, key);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("decoder", new NettyProtocolDecoder());
            pipeline.addLast("encoder", new NettyProtocolEncoder());
            pipeline.addLast("handler", handler);
        }

    });
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync();
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    NettyClient client = new NettyClient(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}