Java 使用netty进行大规模http发布的正确有效方法

Java 使用netty进行大规模http发布的正确有效方法,java,performance,http,out-of-memory,netty,Java,Performance,Http,Out Of Memory,Netty,我需要使用netty 4.1执行大量http发布,其中http主体在所有消息中都是静态的(=始终相同) 我提出了这个(简化的)解决方案,但我不确定这是否是最有效、最高效的方法。问题特别集中在ByteBuf处理和OOM预防上 final String requestBody = "... huge static post content ..."; EventLoopGroup group = new NioEventLoopGroup(); try {

我需要使用netty 4.1执行大量http发布,其中http主体在所有消息中都是静态的(=始终相同)

我提出了这个(简化的)解决方案,但我不确定这是否是最有效、最高效的方法。问题特别集中在ByteBuf处理和OOM预防上

    final String requestBody = "... huge static post content ...";

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpClientInitializer());

        b.option(ChannelOption.TCP_NODELAY, true);

        int requestCount = Integer.MAX_VALUE;
        latch = new CountDownLatch(requestCount);
        ByteBuf requestBodyBuf = Unpooled.copiedBuffer(requestBody, StandardCharsets.UTF_8).asReadOnly();
        DefaultFullHttpRequest postRequest = postRequest(requestBodyBuf);

        Channel ch = b.connect("localhost", 8080).sync().channel();

        //write a lot (and as fast as possible) post messages which are are all equal
        //is .retainedDuplicate() correct and ressource efficient?
        for(int i=0; i<requestCount; i++) {
            ch.writeAndFlush(postRequest.retainedDuplicate());
        }

        latch.await();
        ch.close();
    } finally {
        group.shutdownGracefully();
    }
final String requestBody=“…大量静态帖子内容…”;
EventLoopGroup=new NioEventLoopGroup();
试一试{
引导b=新引导();
b、 group(group).channel(NioSocketChannel.class).handler(新的HttpClientInitializer());
b、 选项(ChannelOption.TCP_NODELAY,true);
int requestCount=Integer.MAX_值;
闩锁=新的倒计时闩锁(requestCount);
ByteBuf requestBodyBuf=unmooled.copiedBuffer(requestBody,StandardCharsets.UTF_8).asReadOnly();
DefaultFullHttpRequest postRequest=postRequest(requestBodyBuf);
Channel ch=b.connect(“localhost”,8080).sync().Channel();
//写很多(并且尽可能快)平等的帖子
//.retainedDuplicate()正确且资源有效吗?

对于(int i=0;i您应将其更改为:

    for(int i=0; i<requestCount; i++) {
        ch.write(postRequest.retainedDuplicate());
    }
    // This will ensure you can do a gathering write (writev).
    ch.flush();

    // As you retain on each write you should release the last reference after done.
    postRequest.release();
for(int i=0;i