Netty作为高性能Http服务器处理大约2-3百万个请求/秒

时间:2017-06-22 20:22:00

标签: java http client-server netty

我们正在尝试解决处理大量Http POST请求的问题,并且在使用Netty Server时,我只能处理过低的~50K requests/sec

我的问题是如何调整此服务器以确保处理> 1.5 million requests/second

Netty4服务器

// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);

        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HttpServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " +
                (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

初始化程序

    public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {

    private final SslContext sslCtx;

    public HttpServerInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        if (sslCtx != null) {
            p.addLast(sslCtx.newHandler(ch.alloc()));
        }
        p.addLast(new HttpServerCodec());
        p.addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE));
        p.addLast(new HttpServerHandler());
    }
}

处理程序

public class HttpServerHandler extends ChannelInboundHandlerAdapter {
private static final String CONTENT = "SUCCESS";

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    ctx.flush();
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        final FullHttpRequest fReq = (FullHttpRequest) req;
        Charset utf8 = CharsetUtil.UTF_8;
        final ByteBuf buf = fReq.content();
        String in = buf.toString( utf8 );
        System.out.println(" In ==> "+in);
        buf.release();
        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        }
        in = null;
        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT.getBytes()));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
{
        cause.printStackTrace();
        ctx.close();
    }

}

1 个答案:

答案 0 :(得分:3)

你的问题很通用。但是,我会尝试为您提供有关netty优化和代码改进的答案。

您的代码问题:

  1. System.out.println(" In ==> "+in); - 你不应该在高负荷并流处理程序中使用它。为什么?因为println方法中的代码是同步的,因此会对您的表现造成惩罚;
  2. 你做2个类演员。致HttpRequestFullHttpRequest。你可以使用最后一个;
  3. 代码中的Netty特定问题:

    1. 您需要添加epoll传输(如果您的服务器像Linux一样)。开箱即可达到+ ~30%; How to
    2. 您需要添加本机OpenSSL绑定。它会给出+ ~20%。 How to
    3. EventLoopGroup bossGroup = new NioEventLoopGroup(); - 您需要正确设置bossGroupworkerGroup组的尺寸。取决于您的测试方案。您没有提供有关测试用例的任何信息,因此我无法在此向您提供建议;
    4. new HttpObjectAggregator(Integer.MAX_VALUE) - 您实际上并不需要在代码中使用此处理程序。因此,为了获得更好的性能,您可以将其删除。
    5. new HttpServerHandler() - 您不需要为每个频道创建此处理程序。由于它没有任何状态,因此可以在所有管道中共享。在netty中搜索@Sharable
    6. new LoggingHandler(LogLevel.INFO) - 您不需要此处理程序进行高负载测试,因为它记录了很多。必要时进行自己的记录;
    7. buf.toString( utf8 ) - 这是非常错误的。您将收入字节转换为字符串。但这并没有任何意义,因为所有数据都已在netty HttpServerCodec中解码。所以你在这里做双重工作;
    8. Unpooled.wrappedBuffer(CONTENT.getBytes()) - 您在每个请求上都包含常量消息。因此 - 对每个请求都做不必要的工作。您只能创建一次ByteBuf并执行retain()duplicate(),具体取决于您执行此操作的方式;
    9. ctx.write(response) - 您可以考虑使用ctx.write(response, ctx.voidPromise())来分配更少的内容;
    10. 这不是全部。但是,解决上述问题将是一个良好的开端。