io.netty.buffer.PooledByteBufAllocator Java Examples

The following examples show how to use io.netty.buffer.PooledByteBufAllocator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BedrockSession.java    From Protocol with Apache License 2.0 6 votes vote down vote up
private byte[] generateTrailer(ByteBuf buf) {
    VoxelwindHash hash = hashLocal.get();
    ByteBuf counterBuf = null;
    ByteBuf keyBuf = null;
    try {
        counterBuf = PooledByteBufAllocator.DEFAULT.directBuffer(8);
        keyBuf = PooledByteBufAllocator.DEFAULT.directBuffer(agreedKey.getEncoded().length);
        counterBuf.writeLongLE(this.sentEncryptedPacketCount.getAndIncrement());
        keyBuf.writeBytes(this.agreedKey.getEncoded());

        hash.update(counterBuf);
        hash.update(buf);
        hash.update(keyBuf);
        byte[] digested = hash.digest();
        return Arrays.copyOf(digested, 8);
    } finally {
        if (counterBuf != null) {
            counterBuf.release();
        }
        if (keyBuf != null) {
            keyBuf.release();
        }
    }
}
 
Example #2
Source File: TransportServerSupport.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
protected ServerBootstrap newBootstrap(ChannelHandler channelHandler, EventLoopGroup acceptEventGroup, EventLoopGroup ioEventGroup) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .group(acceptEventGroup, ioEventGroup)
            .childHandler(channelHandler)
            .option(ChannelOption.SO_REUSEADDR, serverConfig.isReuseAddress())
            .option(ChannelOption.SO_RCVBUF, serverConfig.getSocketBufferSize())
            .option(ChannelOption.SO_BACKLOG, serverConfig.getBacklog())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_SNDBUF, serverConfig.getSocketBufferSize())
            .childOption(ChannelOption.TCP_NODELAY, serverConfig.isTcpNoDelay())
            .childOption(ChannelOption.SO_KEEPALIVE, serverConfig.isKeepAlive())
            .childOption(ChannelOption.SO_LINGER, serverConfig.getSoLinger())
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    return serverBootstrap;
}
 
Example #3
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSslEngineFromJksStoreWithExplicitDisabledCiphersOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    // Discover the default enabled ciphers
    TransportOptions options = createJksSslOptions();
    SSLEngine directEngine = createOpenSSLEngineDirectly(options);
    String[] ciphers = directEngine.getEnabledCipherSuites();
    assertTrue("There were no initial ciphers to choose from!", ciphers.length > 0);

    // Pull out one to disable specifically
    String[] disabledCipher = new String[] { ciphers[ciphers.length - 1] };
    String[] trimmedCiphers = Arrays.copyOf(ciphers, ciphers.length - 1);
    options.setDisabledCipherSuites(disabledCipher);
    SslContext context = TransportSupport.createOpenSslContext(options);
    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);

    // verify the option took effect
    assertNotNull(engine);
    assertArrayEquals("Enabled ciphers not as expected", trimmedCiphers, engine.getEnabledCipherSuites());
}
 
Example #4
Source File: AbstractRedisProxyServerTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
public ChannelFuture connect() throws Exception {

        startServer();
        Bootstrap b = new Bootstrap();
        b.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                });
        return b.connect("127.0.0.1", config.frontendTcpPort());
    }
 
Example #5
Source File: HelloWebServer.java    From crow-benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass) throws InterruptedException {
try {
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next()));
    b.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
    b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
    b.childOption(ChannelOption.SO_REUSEADDR, true);
    b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

    Channel ch = b.bind(port).sync().channel();
    ch.closeFuture().sync();
} finally {
    loupGroup.shutdownGracefully().sync();
}
   }
 
Example #6
Source File: BGPDispatcherImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer<?> initializer) {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    if (Epoll.isAvailable()) {
        serverBootstrap.channel(EpollServerSocketChannel.class);
        serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        serverBootstrap.channel(NioServerSocketChannel.class);
    }
    final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
    serverBootstrap.childHandler(serverChannelHandler);

    serverBootstrap.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WATER_MARK);

    // Make sure we are doing round-robin processing
    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, RECV_ALLOCATOR);

    if (serverBootstrap.config().group() == null) {
        serverBootstrap.group(this.bossGroup, this.workerGroup);
    }
    return serverBootstrap;
}
 
Example #7
Source File: NetworkManager.java    From Ogar2-Server with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    try {
        ch.config().setOption(ChannelOption.IP_TOS, 0x18);
    } catch (ChannelException ex) {
        // IP_TOS not supported by platform, ignore
    }
    ch.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    ch.pipeline().addLast(new HttpServerCodec());
    ch.pipeline().addLast(new HttpObjectAggregator(65536));
    ch.pipeline().addLast(new WebSocketHandler());
    ch.pipeline().addLast(new PacketDecoder());
    ch.pipeline().addLast(new PacketEncoder());
    ch.pipeline().addLast(new ClientHandler(server));
}
 
Example #8
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSslEngineFromJksStoreWithExplicitEnabledAndDisabledCiphersOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    // Discover the default enabled ciphers
    TransportOptions options = createJksSslOptions();
    SSLEngine directEngine = createOpenSSLEngineDirectly(options);
    String[] ciphers = directEngine.getEnabledCipherSuites();
    assertTrue("There werent enough initial ciphers to choose from!", ciphers.length > 1);

    // Pull out two to enable, and one to disable specifically
    String cipher1 = ciphers[0];
    String cipher2 = ciphers[1];
    String[] enabledCiphers = new String[] { cipher1, cipher2 };
    String[] disabledCipher = new String[] { cipher1 };
    String[] remainingCipher = new String[] { cipher2 };
    options.setEnabledCipherSuites(enabledCiphers);
    options.setDisabledCipherSuites(disabledCipher);
    SslContext context = TransportSupport.createOpenSslContext(options);
    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);

    // verify the option took effect, that the disabled ciphers were removed from the enabled list.
    assertNotNull(engine);
    assertArrayEquals("Enabled ciphers not as expected", remainingCipher, engine.getEnabledCipherSuites());
}
 
Example #9
Source File: LZ4CompressionCodec.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuf compress(ByteBuf uncompressed, int headerLen) {
    checkNotNull(uncompressed);
    checkArgument(uncompressed.readableBytes() > 0);

    int uncompressedLen = uncompressed.readableBytes();
    int maxLen = compressor.maxCompressedLength(uncompressedLen);

    // get the source bytebuffer
    ByteBuffer uncompressedNio = uncompressed.nioBuffer(uncompressed.readerIndex(), uncompressedLen);
    ByteBuf compressed = PooledByteBufAllocator.DEFAULT.buffer(
            maxLen + headerLen, maxLen + headerLen);
    ByteBuffer compressedNio = compressed.nioBuffer(headerLen, maxLen);

    int compressedLen = compressor.compress(
            uncompressedNio, uncompressedNio.position(), uncompressedLen,
            compressedNio, compressedNio.position(), maxLen);
    compressed.writerIndex(compressedLen + headerLen);

    return compressed;
}
 
Example #10
Source File: PduCodec.java    From herddb with Apache License 2.0 6 votes vote down vote up
public static ByteBuf write(long messageId, byte[] token) {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
            .directBuffer(
                    VERSION_SIZE
                            + FLAGS_SIZE
                            + TYPE_SIZE
                            + MSGID_SIZE
                            + 1 + (token != null ? token.length : 0));
    byteBuf.writeByte(VERSION_3);
    byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
    byteBuf.writeByte(Pdu.TYPE_SASL_TOKEN_MESSAGE_TOKEN);
    byteBuf.writeLong(messageId);
    if (token == null) {
        byteBuf.writeByte(NULLABLE_FIELD_ABSENT);
    } else {
        byteBuf.writeByte(NULLABLE_FIELD_PRESENT);
        ByteBufUtils.writeArray(byteBuf, token);
    }
    return byteBuf;
}
 
Example #11
Source File: AbstractSslEngineThroughputBenchmark.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Setup(Level.Iteration)
public final void setup() throws Exception {
    ByteBufAllocator allocator = new PooledByteBufAllocator(true);
    initEngines(allocator);
    initHandshakeBuffers();

    wrapDstBuffer = allocateBuffer(clientEngine.getSession().getPacketBufferSize() << 2);
    wrapSrcBuffer = allocateBuffer(messageSize);

    byte[] bytes = new byte[messageSize];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);
    wrapSrcBuffer.put(bytes);
    wrapSrcBuffer.flip();

    // Complete the initial TLS handshake.
    if (!doHandshake()) {
        throw new IllegalStateException();
    }
    doSetup();
}
 
Example #12
Source File: RedisEncoderBenchmark.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Setup(Level.Trial)
public void setup() {
    byte[] bytes = new byte[256];
    content = Unpooled.buffer(bytes.length);
    content.writeBytes(bytes);
    ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());

    List<RedisMessage> rList = new ArrayList<RedisMessage>(arraySize);
    for (int i = 0; i < arraySize; ++i) {
        rList.add(new FullBulkStringRedisMessage(testContent));
    }
    redisArray = new ArrayRedisMessage(rList);
    encoder = new RedisEncoder();
    context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
            UnpooledByteBufAllocator.DEFAULT, encoder) {
        @Override
        protected void handleException(Throwable t) {
            handleUnexpectedException(t);
        }
    };
}
 
Example #13
Source File: NettyMultipartRequestTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link NettyMultipartRequest} with the given {@code headers} and {@code parts}.
 * @param headers the {@link HttpHeaders} that need to be added to the request.
 * @param parts the files that will form the parts of the request.
 * @return a {@link NettyMultipartRequest} containing all the {@code headers} and {@code parts}.
 * @throws Exception
 */
private NettyMultipartRequest createRequest(HttpHeaders headers, InMemoryFile[] parts) throws Exception {
  HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
  if (headers != null) {
    httpRequest.headers().set(headers);
  }
  HttpPostRequestEncoder encoder = createEncoder(httpRequest, parts);
  NettyMultipartRequest request =
      new NettyMultipartRequest(encoder.finalizeRequest(), new MockChannel(), NETTY_METRICS, Collections.emptySet(),
          Long.MAX_VALUE);
  assertTrue("Request channel is not open", request.isOpen());
  while (!encoder.isEndOfInput()) {
    // Sending null for ctx because the encoder is OK with that.
    request.addContent(encoder.readChunk(PooledByteBufAllocator.DEFAULT));
  }
  return request;
}
 
Example #14
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSslEngineFromJceksStoreWithExplicitEnabledProtocolsOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    // Try and disable all but the one we really want but for now expect that this one plus SSLv2Hello
    // is going to come back until the netty code can successfully disable them all.
    TransportOptions options = createJceksSslOptions(ENABLED_PROTOCOLS);

    SslContext context = TransportSupport.createOpenSslContext(options);
    assertNotNull(context);

    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);
    assertNotNull(engine);

    assertArrayEquals("Enabled protocols not as expected", ENABLED_OPENSSL_PROTOCOLS, engine.getEnabledProtocols());
}
 
Example #15
Source File: UDPServerSocket.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        if (Epoll.isAvailable()) {
            bootstrap = new Bootstrap()
                    .channel(EpollDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(this)
                    .group(new EpollEventLoopGroup());
            this.logger.info("Epoll is available. EpollEventLoop will be used.");
        } else {
            bootstrap = new Bootstrap()
                    .group(new NioEventLoopGroup())
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(this);
            this.logger.info("Epoll is unavailable. Reverting to NioEventLoop.");
        }
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example #16
Source File: PduCodec.java    From herddb with Apache License 2.0 6 votes vote down vote up
public static ByteBuf write(long messageId, String tableSpace, List<KeyValue> records) {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT
            .directBuffer(
                    VERSION_SIZE
                            + FLAGS_SIZE
                            + TYPE_SIZE
                            + MSGID_SIZE
                            + tableSpace.length()
                            + records.size() * 512);
    byteBuf.writeByte(VERSION_3);
    byteBuf.writeByte(Pdu.FLAGS_ISREQUEST);
    byteBuf.writeByte(Pdu.TYPE_PUSH_TXLOGCHUNK);
    byteBuf.writeLong(messageId);
    ByteBufUtils.writeString(byteBuf, tableSpace);

    byteBuf.writeInt(records.size());
    for (KeyValue kv : records) {
        ByteBufUtils.writeArray(byteBuf, kv.key);
        ByteBufUtils.writeArray(byteBuf, kv.value);
    }

    return byteBuf;

}
 
Example #17
Source File: Fixtures.java    From tchannel-java with MIT License 6 votes vote down vote up
public static CallResponseFrame callResponse(long id,
                                             boolean moreFragments,
                                             Map<String, String> headers,
                                             ByteBuf payload) {
    CallResponseFrame callResponseFrame = new CallResponseFrame(
            id,
            moreFragments ? (byte) 1 : (byte) 0,
            ResponseCode.OK,
            new Trace(0, 0, 0, (byte) 0x00),
            headers,
            ChecksumType.NoChecksum,
            0,
            null
    );

    ByteBuf byteBuf = callResponseFrame.encodeHeader(PooledByteBufAllocator.DEFAULT);
    callResponseFrame.setPayload(Unpooled.wrappedBuffer(byteBuf, payload));

    checkState(byteBuf.refCnt() == 1);
    return callResponseFrame;
}
 
Example #18
Source File: Fixtures.java    From tchannel-java with MIT License 5 votes vote down vote up
public static CallResponseContinueFrame callResponseContinue(long id, boolean moreFragments, ByteBuf payload) {
    CallResponseContinueFrame callResponseContinueFrame = new CallResponseContinueFrame(
            id,
            moreFragments ? (byte) 1 : (byte) 0,
            ChecksumType.NoChecksum,
            0,
            payload
    );

    ByteBuf byteBuf = callResponseContinueFrame.encodeHeader(PooledByteBufAllocator.DEFAULT);
    callResponseContinueFrame.setPayload(Unpooled.wrappedBuffer(byteBuf, payload));
    checkState(byteBuf.refCnt() == 1);
    return callResponseContinueFrame;
}
 
Example #19
Source File: NettyServerServiceImpl.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void groupsNio(final ServerBootstrap bootstrap, final int workThreads) {
    workerGroup = new NioEventLoopGroup(workThreads);
    bootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(EpollChannelOption.TCP_CORK, true)
            .option(EpollChannelOption.SO_KEEPALIVE, true)
            .option(EpollChannelOption.SO_BACKLOG, 1024)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(nettyServerHandlerInitializer);
}
 
Example #20
Source File: NettyConnector.java    From hasor with Apache License 2.0 5 votes vote down vote up
private <T extends AbstractBootstrap<?, ?>> T configBoot(T boot) {
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    // boot.option(ChannelOption.SO_BACKLOG, 128);
    // boot.option(ChannelOption.SO_BACKLOG, 1024);
    // boot.option(ChannelOption.SO_RCVBUF, 1024 * 256);
    // boot.option(ChannelOption.SO_SNDBUF, 1024 * 256);
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    return boot;
}
 
Example #21
Source File: MemoryLeakDetectionRule.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
private static int getActiveDirectBuffers(PooledByteBufAllocator alloc) {
    int directActive = 0, directAlloc = 0, directDealloc = 0;
    for (PoolArenaMetric arena : alloc.metric().directArenas()) {
        directActive += arena.numActiveAllocations();
        directAlloc += arena.numAllocations();
        directDealloc += arena.numDeallocations();
    }
    log.info("direct memory usage, active: {}, alloc: {}, dealloc: {}", directActive, directAlloc, directDealloc);
    return directActive;
}
 
Example #22
Source File: ByteBufAllocatorMetricsTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
	DisposableServer server =
			HttpServer.create()
			          .port(0)
			          .handle((req, res) -> res.header("Connection", "close")
			                                   .sendString(Mono.just("test")))
			          .bindNow();

	CountDownLatch latch = new CountDownLatch(1);

	PooledByteBufAllocator alloc = new PooledByteBufAllocator(true);
	HttpClient.create()
	          .port(server.port())
	          .option(ChannelOption.ALLOCATOR, alloc)
	          .doOnResponse((res, conn) -> conn.channel()
	                                           .closeFuture()
	                                           .addListener(f -> latch.countDown()))
	          .metrics(true, s -> s)
	          .get()
	          .uri("/")
	          .responseContent()
	          .aggregate()
	          .asString()
	          .block(Duration.ofSeconds(30));

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	String id = alloc.metric().hashCode() + "";
	String[] tags = new String[]{ID, id, TYPE, "pooled"};
	checkExpectations(BYTE_BUF_ALLOCATOR_PREFIX, tags);

	server.disposeNow();
}
 
Example #23
Source File: TChannel.java    From tchannel-java with MIT License 5 votes vote down vote up
private @NotNull Bootstrap bootstrap(@NotNull TChannel topChannel) {
    return new Bootstrap()
        .group(this.childGroup)
        .channel(useEpoll ? EpollSocketChannel.class : NioSocketChannel.class)
        .handler(this.channelInitializer(false, topChannel))
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                new WriteBufferWaterMark(WRITE_BUFFER_LOW_WATER_MARK, WRITE_BUFFER_HIGH_WATER_MARK))
        .validate();
}
 
Example #24
Source File: RSocketClientToServerIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Bean
public RSocketStrategies rsocketStrategies() {
	return RSocketStrategies.builder()
			.decoder(StringDecoder.allMimeTypes())
			.encoder(CharSequenceEncoder.allMimeTypes())
			.dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT))
			.build();
}
 
Example #25
Source File: TChannel.java    From tchannel-java with MIT License 5 votes vote down vote up
private @NotNull ServerBootstrap serverBootstrap(@NotNull TChannel topChannel) {
    return new ServerBootstrap()
        .group(this.bossGroup, this.childGroup)
        .channel(useEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
        .handler(new LoggingHandler(LogLevel.INFO))
        .option(ChannelOption.SO_BACKLOG, 128)
        .childHandler(this.channelInitializer(true, topChannel))
        .childOption(ChannelOption.SO_KEEPALIVE, true)
        .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .childOption(
            ChannelOption.WRITE_BUFFER_WATER_MARK,
            new WriteBufferWaterMark(WRITE_BUFFER_LOW_WATER_MARK, WRITE_BUFFER_HIGH_WATER_MARK)
        )
        .validate();
}
 
Example #26
Source File: NettyServer.java    From nuls with MIT License 5 votes vote down vote up
public void init() {
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
//                .childOption(ChannelOption.SO_BACKLOG, 2048)
                .childOption(ChannelOption.TCP_NODELAY, true)            //Send messages immediately
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_SNDBUF, 128 * 1024)
                .childOption(ChannelOption.SO_RCVBUF, 128 * 1024)
                .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new NulsChannelInitializer<>(new ServerChannelHandler()));
    }
 
Example #27
Source File: PooledDataBufferTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Parameterized.Parameters(name = "{0}")
public static Object[][] buffers() {

	return new Object[][]{
			{new NettyDataBufferFactory(new UnpooledByteBufAllocator(true))},
			{new NettyDataBufferFactory(new UnpooledByteBufAllocator(false))},
			{new NettyDataBufferFactory(new PooledByteBufAllocator(true))},
			{new NettyDataBufferFactory(new PooledByteBufAllocator(false))}};
}
 
Example #28
Source File: ConnClientBoot.java    From mpush with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart(Listener listener) throws Throwable {
    ServiceDiscoveryFactory.create().syncStart();
    CacheManagerFactory.create().init();
    monitorService = new MonitorService();
    EventBus.create(monitorService.getThreadPoolManager().getEventBusExecutor());

    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)//
            .option(ChannelOption.TCP_NODELAY, true)//
            .option(ChannelOption.SO_REUSEADDR, true)//
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60 * 1000)
            .option(ChannelOption.SO_RCVBUF, 5 * 1024 * 1024)
            .channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new PacketDecoder());
            ch.pipeline().addLast("encoder", PacketEncoder.INSTANCE);
            ch.pipeline().addLast("handler", new ConnClientChannelHandler());
        }
    });

    listener.onSuccess();
}
 
Example #29
Source File: RSocketRequesterRpcZipkinProxy.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
protected Flux<Payload> remoteRequestStream(ReactiveMethodMetadata methodMetadata, ByteBuf compositeMetadata, ByteBuf bodyBuf) {
    return Flux.deferWithContext(context -> {
        TraceContext traceContext = context.getOrDefault(TraceContext.class, null);
        if (traceContext != null) {
            CompositeByteBuf newCompositeMetadata = new CompositeByteBuf(PooledByteBufAllocator.DEFAULT, true, 2, compositeMetadata, tracingMetadata(traceContext).getContent());
            Span span = tracer.newChild(traceContext);
            return super.remoteRequestStream(methodMetadata, newCompositeMetadata, bodyBuf)
                    .doOnError(span::error)
                    .doOnComplete(span::finish);
        }
        return super.remoteRequestStream(methodMetadata, compositeMetadata, bodyBuf);
    });
}
 
Example #30
Source File: TransportConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(Channel channel) {
	ChannelPipeline pipeline = channel.pipeline();

	if (config.metricsRecorder != null) {
		ChannelOperations.addMetricsHandler(channel,
				Objects.requireNonNull(config.metricsRecorder.get(), "Metrics recorder supplier returned null"),
				remoteAddress,
				onServer);

		ByteBufAllocator alloc = channel.alloc();
		if (alloc instanceof PooledByteBufAllocator) {
			ByteBufAllocatorMetrics.INSTANCE.registerMetrics("pooled", ((PooledByteBufAllocator) alloc).metric());
		}
		else if (alloc instanceof UnpooledByteBufAllocator) {
			ByteBufAllocatorMetrics.INSTANCE.registerMetrics("unpooled", ((UnpooledByteBufAllocator) alloc).metric());
		}
	}

	if (config.loggingHandler != null) {
		pipeline.addFirst(NettyPipeline.LoggingHandler, config.loggingHandler);
	}

	ChannelOperations.addReactiveBridge(channel, config.channelOperationsProvider(), connectionObserver);

	config.defaultOnChannelInit()
	      .then(config.doOnChannelInit)
	      .onChannelInit(connectionObserver, channel, remoteAddress);

	pipeline.remove(this);

	if (log.isDebugEnabled()) {
		log.debug(format(channel, "Initialized pipeline {}"), pipeline.toString());
	}
}