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:com.ancun.netty.httpserver.HttpServer.java

License:Apache License

private void setBootstrapOptions(ServerBootstrap bootstrap) {
    bootstrap.option(ChannelOption.SO_KEEPALIVE, useKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    bootstrap.option(ChannelOption.TCP_NODELAY, useTcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, serverSettings.isKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
    bootstrap.option(ChannelOption.SO_LINGER, getSoLinger());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeoutMillis());
    bootstrap.option(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

    bootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
    bootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServer.java

License:Apache License

public RpcServer(Class<? extends ServerChannel> serverChannelClass, RpcServerOptions serverOptions,
        RpcServiceRegistry rpcServiceRegistry) {
    if (rpcServiceRegistry == null) {
        throw new RuntimeException("protperty 'rpcServiceRegistry ' is null.");
    }/*from  w ww.j a  v a  2s.c  o  m*/

    if (serverOptions == null) {
        serverOptions = new RpcServerOptions();
    }

    this.bossGroup = new NioEventLoopGroup(serverOptions.getAcceptorThreads());
    this.workerGroup = new NioEventLoopGroup(serverOptions.getWorkThreads());
    this.group(this.bossGroup, this.workerGroup);
    this.channel(serverChannelClass);

    this.option(ChannelOption.SO_BACKLOG, serverOptions.getBacklog());

    this.childOption(ChannelOption.SO_KEEPALIVE, serverOptions.isKeepAlive());
    this.childOption(ChannelOption.SO_REUSEADDR, true);
    this.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    this.childOption(ChannelOption.TCP_NODELAY, serverOptions.isTcpNoDelay());
    this.childOption(ChannelOption.SO_LINGER, serverOptions.getSoLinger());
    this.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, serverOptions.getConnectTimeout());
    this.childOption(ChannelOption.SO_RCVBUF, serverOptions.getReceiveBufferSize());
    this.childOption(ChannelOption.SO_SNDBUF, serverOptions.getSendBufferSize());

    this.rpcServiceRegistry = rpcServiceRegistry;
    // do register meta service
    rpcServiceRegistry.doRegisterMetaService();
    this.rpcServerOptions = serverOptions;
    this.rpcServerPipelineInitializer = new RpcServerPipelineInitializer(rpcServiceRegistry, rpcServerOptions);
    this.childHandler(rpcServerPipelineInitializer);
}

From source file:com.caocao.nio.server.NettyServer.java

License:Apache License

public void initAndStart() {
    System.out.println("port:" + port);
    // Configure the server.
    bossGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
    try {//from   ww  w  .  ja  v  a  2s .c  o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, 5 * 1024)
                .option(ChannelOption.SO_SNDBUF, 5 * 1024)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(40, 64, 1024))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new CustomerInitializer());

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("netty??", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.caricah.iotracah.server.netty.ServerImpl.java

License:Apache License

/**
 * The @link configure method is responsible for starting the implementation server processes.
 * The implementation should return once the server has started this allows
 * the launcher to maintain the life of the application.
 *
 * @throws UnRetriableException/*  www.  java 2s. c  o  m*/
 */
public void initiate() throws UnRetriableException {

    log.info(" configure : initiating the netty server.");

    try {

        int countOfAvailableProcessors = Runtime.getRuntime().availableProcessors() + 1;

        if (Epoll.isAvailable()) {
            bossEventLoopGroup = new EpollEventLoopGroup(2, getExecutorService());
            workerEventLoopGroup = new EpollEventLoopGroup(countOfAvailableProcessors, getExecutorService());

        } else {
            bossEventLoopGroup = new NioEventLoopGroup(2, getExecutorService());
            workerEventLoopGroup = new NioEventLoopGroup(countOfAvailableProcessors, getExecutorService());
        }

        //Initialize listener for TCP
        ServerBootstrap tcpBootstrap = new ServerBootstrap();
        tcpBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        tcpBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
        tcpBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

        tcpBootstrap = tcpBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

        if (Epoll.isAvailable()) {
            tcpBootstrap = tcpBootstrap.channel(EpollServerSocketChannel.class);
        } else {
            tcpBootstrap = tcpBootstrap.channel(NioServerSocketChannel.class);
        }

        tcpBootstrap = tcpBootstrap.handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(getServerInitializer(this, getConnectionTimeout()));

        ChannelFuture tcpChannelFuture = tcpBootstrap.bind(getTcpPort()).sync();
        tcpChannel = tcpChannelFuture.channel();

        if (isSslEnabled()) {
            //Initialize listener for SSL
            ServerBootstrap sslBootstrap = new ServerBootstrap();
            sslBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            sslBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
            sslBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

            sslBootstrap = sslBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

            if (Epoll.isAvailable()) {
                sslBootstrap = sslBootstrap.channel(EpollServerSocketChannel.class);
            } else {
                sslBootstrap = sslBootstrap.channel(NioServerSocketChannel.class);
            }

            sslBootstrap = sslBootstrap.handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(getServerInitializer(this, getConnectionTimeout(), getSslHandler()));

            ChannelFuture sslChannelFuture = sslBootstrap.bind(getSslPort()).sync();
            sslChannel = sslChannelFuture.channel();
        }

    } catch (InterruptedException e) {

        log.error(" configure : Initialization issues ", e);

        throw new UnRetriableException(e);

    }

}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {//  w  w w  .  j av a2s.  c om

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        // Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel()));

        final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY)
                .get().getRemote();//from   ww  w . ja v  a 2 s.c  o m

        bootstrap
                .connect(apnProxyRemote.getInetSocketAddress(),
                        new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0))
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                    HttpVersion.HTTP_1_1,
                                    new HttpResponseStatus(200, "Connection established"));
                            uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                    .addListener(new ChannelFutureListener() {
                                        @Override
                                        public void operationComplete(ChannelFuture future2) throws Exception {
                                            // remove handlers
                                            uaChannelCtx.pipeline().remove("codec");
                                            uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME);
                                            uaChannelCtx.pipeline()
                                                    .remove(HttpUserAgentTunnelHandler.HANDLER_NAME);

                                            uaChannelCtx.pipeline()
                                                    .addLast(new HttpRelayHandler(
                                                            "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                            future1.channel()));
                                        }

                                    });

                        } else {
                            if (uaChannelCtx.channel().isActive()) {
                                uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

    }
    ReferenceCountUtil.release(msg);
}

From source file:com.codebroker.core.service.NettyNetService.java

License:Open Source License

@Override
public void init(Object object) {
    logger.info("?Netty ");
    PropertiesWrapper propertiesWrapper = (PropertiesWrapper) object;

    int defaultValue = Runtime.getRuntime().availableProcessors() * 2;

    bossGroupNum = propertiesWrapper.getIntProperty(SystemEnvironment.NETTY_BOSS_GROUP_NUM, defaultValue);
    workerGroupNum = propertiesWrapper.getIntProperty(SystemEnvironment.NETTY_WORKER_GROUP_NUM, defaultValue);
    backlog = propertiesWrapper.getIntProperty(SystemEnvironment.NETTY_BACKLOG, BACKLOG);

    name = propertiesWrapper.getProperty(SystemEnvironment.NETTY_SERVER_NAME, "NETTY_SERVER");
    int port = propertiesWrapper.getIntProperty(SystemEnvironment.TCP_PROT, D_PORT);
    Thread thread = new Thread(new Runnable() {
        public void run() {
            bootstrap = new ServerBootstrap();
            bossGroup = new NioEventLoopGroup(bossGroupNum);
            workerGroup = new NioEventLoopGroup(workerGroupNum);
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, backlog)
                    .option(ChannelOption.SO_REUSEADDR, Boolean.valueOf(true))
                    // .option(ChannelOption.TCP_NODELAY,
                    // Boolean.valueOf(true))
                    // .option(ChannelOption.SO_KEEPALIVE,
                    // Boolean.valueOf(true))
                    .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
                    .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new NettyServerInitializer());
            ChannelFuture f;//  w  w  w .ja v a  2 s  .  c o m
            try {
                f = bootstrap.bind(port).sync();
                f.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "Netty-Start-Thread");
    thread.start();
    logger.info("?Netty ?");
    super.setActive();
}

From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java

License:Apache License

/**
 * Create a new {@link AbstractEndpoint}.
 *
 * @param hostname the hostname/ipaddr of the remote channel.
 * @param bucket the name of the bucket.
 * @param password the password of the bucket.
 * @param port the port of the remote channel.
 * @param environment the environment of the core.
 * @param responseBuffer the response buffer for passing responses up the stack.
 *//* w  w  w  .j av a 2 s  .  c o  m*/
protected AbstractEndpoint(final String hostname, final String bucket, final String password, final int port,
        final CoreEnvironment environment, final RingBuffer<ResponseEvent> responseBuffer,
        boolean isTransient) {
    super(LifecycleState.DISCONNECTED);
    this.bucket = bucket;
    this.password = password;
    this.responseBuffer = responseBuffer;
    this.env = environment;
    this.isTransient = isTransient;
    if (environment.sslEnabled()) {
        this.sslEngineFactory = new SSLEngineFactory(environment);
    }

    Class<? extends Channel> channelClass = NioSocketChannel.class;
    if (environment.ioPool() instanceof EpollEventLoopGroup) {
        channelClass = EpollSocketChannel.class;
    } else if (environment.ioPool() instanceof OioEventLoopGroup) {
        channelClass = OioSocketChannel.class;
    }

    ByteBufAllocator allocator = env.bufferPoolingEnabled() ? PooledByteBufAllocator.DEFAULT
            : UnpooledByteBufAllocator.DEFAULT;

    boolean tcpNodelay = environment().tcpNodelayEnabled();
    bootstrap = new BootstrapAdapter(
            new Bootstrap().remoteAddress(hostname, port).group(environment.ioPool()).channel(channelClass)
                    .option(ChannelOption.ALLOCATOR, allocator).option(ChannelOption.TCP_NODELAY, tcpNodelay)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, env.socketConnectTimeout())
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            if (environment.sslEnabled()) {
                                pipeline.addLast(new SslHandler(sslEngineFactory.get()));
                            }
                            if (LOGGER.isTraceEnabled()) {
                                pipeline.addLast(LOGGING_HANDLER_INSTANCE);
                            }
                            customEndpointHandlers(pipeline);
                        }
                    }));
}

From source file:com.couchbase.client.core.io.endpoint.AbstractEndpoint.java

License:Open Source License

/**
 * Create a new {@link AbstractEndpoint} and supply essential params.
 *
 * @param addr the socket address to connect to.
 * @param env the environment to attach to.
 * @param group the {@link EventLoopGroup} to use.
 *//*from   w  w w.jav a  2s.  c  om*/
protected AbstractEndpoint(final InetSocketAddress addr, final Environment env, final EventLoopGroup group) {
    this.env = env;
    endpointStateDeferred = Streams.defer(env, defaultPromiseEnv);
    endpointStateStream = endpointStateDeferred.compose();

    connectionBootstrap = new BootstrapAdapter(new Bootstrap().group(group).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(final SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (LOGGER.isTraceEnabled()) {
                        pipeline.addLast(new LoggingHandler(LogLevel.TRACE));
                    }

                    customEndpointHandlers(pipeline);
                    pipeline.addLast(new GenericEndpointHandler<REQ, RES>());
                }
            }).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1500)
            .remoteAddress(addr));
}

From source file:com.datastax.driver.core.NettyOptions.java

License:Apache License

/**
 * Hook invoked each time the driver creates a new {@link Connection}
 * and configures a new instance of {@link Bootstrap} for it.
 * <p/>/*w  w w. ja v a  2  s .  c om*/
 * This hook is guaranteed to be called <em>after</em> the driver has applied all
 * {@link SocketOptions}s.
 * <p/>
 * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelOption}s to the boostrap; e.g.
 * plug a custom {@link io.netty.buffer.ByteBufAllocator ByteBufAllocator} implementation:
 * <p/>
 * <pre>
 * ByteBufAllocator myCustomByteBufAllocator = ...
 *
 * public void afterBootstrapInitialized(Bootstrap bootstrap) {
 *     bootstrap.option(ChannelOption.ALLOCATOR, myCustomByteBufAllocator);
 * }
 * </pre>
 * <p/>
 * Note that the default implementation of this method configures a pooled {@code ByteBufAllocator} (Netty 4.0
 * defaults to unpooled). If you override this method to set unrelated options, make sure you call
 * {@code super.afterBootstrapInitialized(bootstrap)}.
 *
 * @param bootstrap the {@link Bootstrap} being initialized.
 */
public void afterBootstrapInitialized(Bootstrap bootstrap) {
    // In Netty 4.1.x, pooled will be the default, so this won't be necessary anymore
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}