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:code.google.nfs.rpc.netty.server.NettyServer.java

License:Apache License

public NettyServer() {
    ThreadFactory serverBossTF = new NamedThreadFactory("NETTYSERVER-BOSS-");
    ThreadFactory serverWorkerTF = new NamedThreadFactory("NETTYSERVER-WORKER-");
    EventLoopGroup bossGroup = new NioEventLoopGroup(PROCESSORS, serverBossTF);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup(PROCESSORS * 2, serverWorkerTF);
    workerGroup.setIoRatio(Integer.parseInt(System.getProperty("nfs.rpc.io.ratio", "50")));
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")))
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")));
}

From source file:com.addthis.hydra.query.web.QueryServer.java

License:Apache License

public void run() throws Exception {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    executorGroup = new DefaultEventExecutorGroup(AggregateConfig.FRAME_READER_THREADS,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("frame-reader-%d").build());
    for (EventExecutor executor : executorGroup) {
        executor.execute(new NextQueryTask(queryQueue, executor));
    }// w  ww. j  ava  2s  .c o m
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.childOption(ChannelOption.MESSAGE_SIZE_ESTIMATOR, new DefaultMessageSizeEstimator(200));
    b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 100000000);
    b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 50000000);
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(queryServerInitializer);
    b.bind(webPort).sync();
}

From source file:com.addthis.meshy.Meshy.java

License:Apache License

protected Meshy() {
    if (HOSTNAME != null) {
        uuid = HOSTNAME + "-" + Long.toHexString(System.currentTimeMillis() & 0xffffff);
    } else {//  ww w.  j av  a 2 s.com
        uuid = Long.toHexString(UUID.randomUUID().getMostSignificantBits());
    }
    workerGroup = new NioEventLoopGroup();
    clientBootstrap = new Bootstrap().option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK).channel(NioSocketChannel.class)
            .group(workerGroup).handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(Meshy.this, ch));
                }
            });
    updateLastEventTime();
}

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group)
        throws IOException {
    super();//  w  ww .j  a  v a  2s  .  co  m
    this.group = group;
    this.rootDir = rootDir;
    this.filesystems = loadFileSystems(rootDir);
    this.serverPeers = new AtomicInteger(0);
    bossGroup = new NioEventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap()
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK)
            .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch));
                }
            });
    /* bind to one or more interfaces, if supplied, otherwise all */
    if ((netif == null) || (netif.length == 0)) {
        ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port))
                .syncUninterruptibly().channel();
        serverLocal = serverChannel.localAddress();
    } else {
        InetSocketAddress primaryServerLocal = null;
        for (String net : netif) {
            NetworkInterface nicif = NetworkInterface.getByName(net);
            if (nicif == null) {
                log.warn("missing speficied NIC: {}", net);
                continue;
            }
            for (InterfaceAddress addr : nicif.getInterfaceAddresses()) {
                InetAddress inAddr = addr.getAddress();
                if (inAddr.getAddress().length != 4) {
                    log.trace("skip non-ipV4 address: {}", inAddr);
                    continue;
                }
                ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap
                        .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel();
                if (primaryServerLocal != null) {
                    log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal);
                }
                primaryServerLocal = serverChannel.localAddress();
            }
        }
        if (primaryServerLocal == null) {
            throw new IllegalArgumentException("no valid interface / port specified");
        }
        serverLocal = primaryServerLocal;
    }
    this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress());
    this.serverPort = serverLocal.getPort();
    if (serverNetIf != null) {
        serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName();
    } else {
        serverUuid = super.getUUID() + "-" + serverPort;
    }
    log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir);
    closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
    workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> {
        bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> {
            if (!workerFuture.isSuccess()) {
                closeFuture.tryFailure(workerFuture.cause());
            } else if (!bossFuture.isSuccess()) {
                closeFuture.tryFailure(bossFuture.cause());
            } else {
                closeFuture.trySuccess(null);
            }
        });
    });
    addMessageFileSystemPaths();
    group.join(this);
    if (autoMesh) {
        startAutoMesh(serverPort, autoMeshTimeout);
    }
}

From source file:com.alibaba.dubbo.remoting.transport.netty.NettyClient.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this);
    bootstrap = new Bootstrap();
    bootstrap.group(nioEventLoopGroup).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout())
            .channel(NioSocketChannel.class);

    if (getTimeout() < 3000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
    } else {//from  w w  w. j  a  va  2s  . c o m
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    }

    bootstrap.handler(new ChannelInitializer() {

        protected void initChannel(Channel ch) throws Exception {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                    .addLast("decoder", adapter.getDecoder())//
                    .addLast("encoder", adapter.getEncoder())//
                    .addLast("handler", nettyClientHandler);
        }
    });
}

From source file:com.alibaba.dubbo.remoting.transport.netty.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    //netty4//from  w w  w  .j av a 2 s. c om
    bootstrap = new ServerBootstrap();
    //1?
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    //       cpu*2 
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            //                
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.alibaba.dubbo.remoting.transport.netty4.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();

    bootstrap = new ServerBootstrap();

    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override// www  .j  ava2s. c  o m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.alibaba.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/*w w  w .  j  a  v a  2s. c o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker);
    if (isLinux) {
        childHandler.channel(EpollServerSocketChannel.class);
    } else {
        childHandler.channel(NioServerSocketChannel.class);
    }
    if (isLinux) {
        childHandler.option(EpollChannelOption.SO_REUSEPORT, true);
    }
    //
    childHandler.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();
    }

    // ?1??
    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:com.alibaba.rocketmq.remoting.netty.NettyUDPServer.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//www.  ja v a 2  s .  c  o  m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupWorker).channel(NioDatagramChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .option(ChannelOption.SO_BROADCAST, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenUDPPort()))
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        public void initChannel(DatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new UDP2BufAdapt(), new NettyEncoder(), //
                                    //
                                    //new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),//
                                    //new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.option(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();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

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

From source file:com.allanbank.mongodb.netty.NettyTransportFactory.java

License:Apache License

/**
 * Creates a new {@link Bootstrap} for creating a Netty client
 * {@link Channel channels}./* www .  j  av a  2  s .  c o  m*/
 *
 * @param config
 *            The configuration for the client.
 * @return The {@link Bootstrap} to create Netty client channels.
 */
protected Bootstrap createBootstrap(final MongoClientConfiguration config) {
    final Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.ALLOCATOR, myBufferAllocator);
    bootstrap.group(myGroup);

    // Suggested defaults.
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

    // Settings from the config.
    bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(config.isUsingSoKeepalive()));
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Integer.valueOf(config.getConnectTimeout()));

    return bootstrap;
}