List of usage examples for io.netty.channel ChannelOption ALLOCATOR
ChannelOption ALLOCATOR
To view the source code for io.netty.channel ChannelOption ALLOCATOR.
Click Source Link
From source file:org.apache.activemq.core.remoting.impl.netty.NettyConnector.java
License:Apache License
public synchronized void start() { if (channelClazz != null) { return;//from w w w. java 2 s . c o m } int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } if (useNioGlobalWorkerPool) { channelClazz = NioSocketChannel.class; group = SharedNioEventLoopGroup.getInstance(threadsToUse); } else { channelClazz = NioSocketChannel.class; group = new NioEventLoopGroup(threadsToUse); } // if we are a servlet wrap the socketChannelFactory bootstrap = new Bootstrap(); bootstrap.channel(channelClazz); bootstrap.group(group); bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay); if (connectTimeoutMillis != -1) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis); } if (tcpReceiveBufferSize != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); } bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false)); channelGroup = new DefaultChannelGroup("activemq-connector", GlobalEventExecutor.INSTANCE); final SSLContext context; if (sslEnabled) { try { // HORNETQ-680 - override the server-side config if client-side system properties are set String realKeyStorePath = keyStorePath; String realKeyStoreProvider = keyStoreProvider; String realKeyStorePassword = keyStorePassword; if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME); } if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME); } if (System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME) != null) { realKeyStoreProvider = System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME); } if (System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME); } if (System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME); } String realTrustStorePath = trustStorePath; String realTrustStoreProvider = trustStoreProvider; String realTrustStorePassword = trustStorePassword; if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME); } if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME); } if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) { realTrustStoreProvider = System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME); } if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME); } if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME); } context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword); } catch (Exception e) { close(); IllegalStateException ise = new IllegalStateException( "Unable to create NettyConnector for " + host + ":" + port); ise.initCause(e); throw ise; } } else { context = null; // Unused } if (context != null && useServlet) { // TODO: Fix me //bootstrap.setOption("sslContext", context); } bootstrap.handler(new ChannelInitializer<Channel>() { public void initChannel(Channel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (sslEnabled && !useServlet) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); // setting the enabled cipher suites resets the enabled protocols so we need // to save the enabled protocols so that after the customer cipher suite is enabled // we can reset the enabled protocols if a customer protocol isn't specified String[] originalProtocols = engine.getEnabledProtocols(); if (enabledCipherSuites != null) { try { engine.setEnabledCipherSuites( SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites)); } catch (IllegalArgumentException e) { ActiveMQClientLogger.LOGGER.invalidCipherSuite(SSLSupport .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } if (enabledProtocols != null) { try { engine.setEnabledProtocols( SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } catch (IllegalArgumentException e) { ActiveMQClientLogger.LOGGER.invalidProtocol( SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } else { engine.setEnabledProtocols(originalProtocols); } SslHandler handler = new SslHandler(engine); pipeline.addLast(handler); } if (httpEnabled) { pipeline.addLast(new HttpRequestEncoder()); pipeline.addLast(new HttpResponseDecoder()); pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); pipeline.addLast(new HttpHandler()); } if (httpUpgradeEnabled) { // prepare to handle a HTTP 101 response to upgrade the protocol. final HttpClientCodec httpClientCodec = new HttpClientCodec(); pipeline.addLast(httpClientCodec); pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec)); } protocolManager.addChannelHandlers(pipeline); pipeline.addLast(new ActiveMQClientChannelHandler(channelGroup, handler, new Listener())); } }); if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } ActiveMQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION); }
From source file:org.apache.activemq.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java
License:Apache License
private void startWebServer(int port) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//ww w. j a va 2 s .c om protected void initChannel(SocketChannel ch) throws Exception { // create a HTTP server ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() { // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ remoting. @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; for (Map.Entry<String, String> entry : request.headers()) { System.out.println(entry); } String upgrade = request.headers().get(UPGRADE); String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); response.headers().set(UPGRADE, upgrade); response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); ctx.writeAndFlush(response); // when the handshake is successful, the HTTP handlers are removed ctx.pipeline().remove("decoder"); ctx.pipeline().remove("encoder"); ctx.pipeline().remove(this); System.out.println("HTTP handshake sent, transferring channel"); // transfer the control of the channel to the Netty Acceptor NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService() .getAcceptor(acceptorName); acceptor.transfer(ctx.channel()); // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. } } }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }); b.bind(port).sync(); }
From source file:org.apache.activemq.transport.amqp.client.transport.NettyTcpTransport.java
License:Apache License
private void configureNetty(Bootstrap bootstrap, NettyTransportOptions 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 ww. ja va 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.bookkeeper.proto.BookieNettyServer.java
License:Apache License
private void listenOn(InetSocketAddress address, BookieSocketAddress bookieAddress) throws InterruptedException { if (!conf.isDisableServerSocketBind()) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.childOption(ChannelOption.ALLOCATOR, allocator); bootstrap.group(eventLoopGroup, eventLoopGroup); bootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay()); bootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger()); bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax())); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark())); if (eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.channel(EpollServerSocketChannel.class); } else {//from w w w .j a v a2s .com bootstrap.channel(NioServerSocketChannel.class); } bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { synchronized (suspensionLock) { while (suspended) { suspensionLock.wait(); } } BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler(); ChannelPipeline pipeline = ch.pipeline(); // For ByteBufList, skip the usual LengthFieldPrepender and have the encoder itself to add it pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE); pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("lengthprepender", new LengthFieldPrepender(4)); pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry)); pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler( contextHandler.getConnectionPeer(), authProviderFactory)); ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler(); pipeline.addLast("bookieRequestHandler", requestHandler); pipeline.addLast("contextHandler", contextHandler); } }); // Bind and start to accept incoming connections Channel listen = bootstrap.bind(address.getAddress(), address.getPort()).sync().channel(); if (listen.localAddress() instanceof InetSocketAddress) { if (conf.getBookiePort() == 0) { conf.setBookiePort(((InetSocketAddress) listen.localAddress()).getPort()); } } } if (conf.isEnableLocalTransport()) { ServerBootstrap jvmBootstrap = new ServerBootstrap(); jvmBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)); jvmBootstrap.group(jvmEventLoopGroup, jvmEventLoopGroup); jvmBootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay()); jvmBootstrap.childOption(ChannelOption.SO_KEEPALIVE, conf.getServerSockKeepalive()); jvmBootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger()); jvmBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax())); jvmBootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark())); if (jvmEventLoopGroup instanceof DefaultEventLoopGroup) { jvmBootstrap.channel(LocalServerChannel.class); } else if (jvmEventLoopGroup instanceof EpollEventLoopGroup) { jvmBootstrap.channel(EpollServerSocketChannel.class); } else { jvmBootstrap.channel(NioServerSocketChannel.class); } jvmBootstrap.childHandler(new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) throws Exception { synchronized (suspensionLock) { while (suspended) { suspensionLock.wait(); } } BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler(); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("lengthprepender", new LengthFieldPrepender(4)); pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry)); pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler( contextHandler.getConnectionPeer(), authProviderFactory)); ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler(); pipeline.addLast("bookieRequestHandler", requestHandler); pipeline.addLast("contextHandler", contextHandler); } }); // use the same address 'name', so clients can find local Bookie still discovering them using ZK jvmBootstrap.bind(bookieAddress.getLocalAddress()).sync(); LocalBookiesRegistry.registerLocalBookieAddress(bookieAddress); } }
From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java
License:Apache License
protected ChannelFuture connect() { final long startTime = MathUtils.nowInNano(); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to bookie: {}", addr); }//w w w . j av a2s . c o m // Set up the ClientBootStrap so we can create a new Channel connection to the bookie. Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup); if (eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.channel(EpollSocketChannel.class); } else if (eventLoopGroup instanceof DefaultEventLoopGroup) { bootstrap.channel(LocalChannel.class); } else { bootstrap.channel(NioSocketChannel.class); } bootstrap.option(ChannelOption.ALLOCATOR, this.allocator); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getClientConnectTimeoutMillis()); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getClientWriteBufferLowWaterMark(), conf.getClientWriteBufferHighWaterMark())); if (!(eventLoopGroup instanceof DefaultEventLoopGroup)) { bootstrap.option(ChannelOption.TCP_NODELAY, conf.getClientTcpNoDelay()); bootstrap.option(ChannelOption.SO_KEEPALIVE, conf.getClientSockKeepalive()); // if buffer sizes are 0, let OS auto-tune it if (conf.getClientSendBufferSize() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, conf.getClientSendBufferSize()); } if (conf.getClientReceiveBufferSize() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, conf.getClientReceiveBufferSize()); } } // In the netty pipeline, we need to split packets based on length, so we // use the {@link LengthFieldBasedFramDecoder}. Other than that all actions // are carried out in this class, e.g., making sense of received messages, // prepending the length to outgoing packets etc. bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE); pipeline.addLast("lengthbasedframedecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("lengthprepender", new LengthFieldPrepender(4)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.RequestEncoder(extRegistry)); pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.ResponseDecoder(extRegistry, useV2WireProtocol)); pipeline.addLast("authHandler", new AuthHandler.ClientSideHandler(authProviderFactory, txnIdGenerator, connectionPeer, useV2WireProtocol)); pipeline.addLast("mainhandler", PerChannelBookieClient.this); } }); SocketAddress bookieAddr = addr.getSocketAddress(); if (eventLoopGroup instanceof DefaultEventLoopGroup) { bookieAddr = addr.getLocalAddress(); } ChannelFuture future = bootstrap.connect(bookieAddr); future.addListener(contextPreservingListener(new ConnectionFutureListener(startTime))); future.addListener(x -> makeWritable()); return future; }
From source file:org.apache.cassandra.transport.Server.java
License:Apache License
private void run() { // Configure the server. eventExecutorGroup = new RequestThreadPoolExecutor(); boolean hasEpoll = enableEpoll ? Epoll.isAvailable() : false; if (hasEpoll) { workerGroup = new EpollEventLoopGroup(); logger.info("Netty using native Epoll event loop"); } else {//from w w w.j a v a 2 s.c o m workerGroup = new NioEventLoopGroup(); logger.info("Netty using Java NIO event loop"); } ServerBootstrap bootstrap = new ServerBootstrap().group(workerGroup) .channel(hasEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_LINGER, 0) .childOption(ChannelOption.SO_KEEPALIVE, DatabaseDescriptor.getRpcKeepAlive()) .childOption(ChannelOption.ALLOCATOR, CBUtil.allocator) .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024) .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); final EncryptionOptions.ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions(); if (clientEnc.enabled) { logger.info("Enabling encrypted CQL connections between client and server"); bootstrap.childHandler(new SecureInitializer(this, clientEnc)); } else { bootstrap.childHandler(new Initializer(this)); } // Bind and start to accept incoming connections. logger.info("Using Netty Version: {}", Version.identify().entrySet()); logger.info("Starting listening for CQL clients on {}...", socket); ChannelFuture bindFuture = bootstrap.bind(socket); if (!bindFuture.awaitUninterruptibly().isSuccess()) throw new IllegalStateException(String.format("Failed to bind port %d on %s.", socket.getPort(), socket.getAddress().getHostAddress())); connectionTracker.allChannels.add(bindFuture.channel()); isRunning.set(true); StorageService.instance.setRpcReady(true); }
From source file:org.apache.drill.exec.rpc.BasicClient.java
License:Apache License
public BasicClient(RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup, T handshakeType, Class<HANDSHAKE_RESPONSE> responseClass, Parser<HANDSHAKE_RESPONSE> handshakeParser) { super(rpcMapping); this.responseClass = responseClass; this.handshakeType = handshakeType; this.handshakeParser = handshakeParser; final long timeoutInMillis = rpcMapping.hasTimeout() ? (long) (rpcMapping.getTimeout() * 1000.0 * PERCENT_TIMEOUT_BEFORE_SENDING_PING) : -1;// w w w . ja v a 2s .co m this.pingHandler = rpcMapping.hasTimeout() ? new IdlePingHandler(timeoutInMillis) : null; b = new Bootstrap() // .group(eventLoopGroup) // .channel(TransportCheck.getClientSocketChannel()) // .option(ChannelOption.ALLOCATOR, alloc) // .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30 * 1000).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_RCVBUF, 1 << 17) // .option(ChannelOption.SO_SNDBUF, 1 << 17) // .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // logger.debug("initializing client connection."); connection = initRemoteConnection(ch); ch.closeFuture().addListener(getCloseHandler(ch, connection)); final ChannelPipeline pipe = ch.pipeline(); pipe.addLast("protocol-decoder", getDecoder(connection.getAllocator())); pipe.addLast("message-decoder", new RpcDecoder("c-" + rpcConfig.getName())); pipe.addLast("protocol-encoder", new RpcEncoder("c-" + rpcConfig.getName())); pipe.addLast("handshake-handler", new ClientHandshakeHandler(connection)); if (pingHandler != null) { pipe.addLast("idle-state-handler", pingHandler); } pipe.addLast("message-handler", new InboundHandler(connection)); pipe.addLast("exception-handler", new RpcExceptionHandler<R>(connection)); } }); // // if(TransportCheck.SUPPORTS_EPOLL){ // b.option(EpollChannelOption.SO_REUSEPORT, true); // // } }
From source file:org.apache.drill.exec.rpc.BasicServer.java
License:Apache License
public BasicServer(final RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup) { super(rpcMapping); this.eventLoopGroup = eventLoopGroup; b = new ServerBootstrap().channel(TransportCheck.getServerSocketChannel()) .option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30 * 1000) .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_RCVBUF, 1 << 17).option(ChannelOption.SO_SNDBUF, 1 << 17) .group(eventLoopGroup) // .childOption(ChannelOption.ALLOCATOR, alloc) // .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override// w w w . j a va 2 s. c o m protected void initChannel(SocketChannel ch) throws Exception { // logger.debug("Starting initialization of server connection."); C connection = initRemoteConnection(ch); ch.closeFuture().addListener(getCloseHandler(ch, connection)); final ChannelPipeline pipe = ch.pipeline(); pipe.addLast("protocol-decoder", getDecoder(connection.getAllocator(), getOutOfMemoryHandler())); pipe.addLast("message-decoder", new RpcDecoder("s-" + rpcConfig.getName())); pipe.addLast("protocol-encoder", new RpcEncoder("s-" + rpcConfig.getName())); pipe.addLast("handshake-handler", getHandshakeHandler(connection)); if (rpcMapping.hasTimeout()) { pipe.addLast(TIMEOUT_HANDLER, new LogggingReadTimeoutHandler(connection, rpcMapping.getTimeout())); } pipe.addLast("message-handler", new InboundHandler(connection)); pipe.addLast("exception-handler", new RpcExceptionHandler<C>(connection)); connect = true; // logger.debug("Server connection initialization completed."); } }); // if(TransportCheck.SUPPORTS_EPOLL){ // b.option(EpollChannelOption.SO_REUSEPORT, true); // // } }
From source file:org.apache.dubbo.remoting.transport.netty4.NettyClient.java
License:Apache License
/** * Init bootstrap// ww w. j a v a2 s. c o m * * @throws Throwable */ @Override protected void doOpen() throws Throwable { 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 (getConnectTimeout() < 3000) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000); } else { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout()); } bootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { int heartbeatInterval = UrlUtils.getHeartbeat(getUrl()); 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("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) .addLast("handler", nettyClientHandler); String socksProxyHost = ConfigUtils.getProperty(SOCKS_PROXY_HOST); if (socksProxyHost != null) { int socksProxyPort = Integer .parseInt(ConfigUtils.getProperty(SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT)); Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler( new InetSocketAddress(socksProxyHost, socksProxyPort)); ch.pipeline().addFirst(socks5ProxyHandler); } } }); }
From source file:org.apache.dubbo.remoting.transport.netty4.NettyServer.java
License:Apache License
/** * Init and start netty server//w w w. j ava2 s.com * * @throws Throwable */ @Override protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true)); workerGroup = new NioEventLoopGroup( getUrl().getPositiveParameter(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 protected void initChannel(NioSocketChannel ch) throws Exception { // FIXME: should we use getTimeout()? int idleTimeout = UrlUtils.getIdleTimeout(getUrl()); 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("server-idle-handler", new IdleStateHandler(0, 0, idleTimeout, MILLISECONDS)) .addLast("handler", nettyServerHandler); } }); // bind ChannelFuture channelFuture = bootstrap.bind(getBindAddress()); channelFuture.syncUninterruptibly(); channel = channelFuture.channel(); }