【问题标题】:How do I handle http requests larger than 1024 bytes in netty?如何在netty中处理大于1024字节的http请求?
【发布时间】:2015-02-18 11:15:38
【问题描述】:

我正在使用 Netty 编写一个简单的反向代理。因为我不想自己处理原始字节,所以我在处理程序管道中添加了一个请求解码器和对象聚合器,以及一个响应编码器,最后是我自己的处理程序,就像这样

ChannelPipeline p = ch.pipeline();
p.addLast(new HttpRequestDecoder());
p.addLast(new HttpObjectAggregator(MAX_CONTENT_LENGTH));
p.addLast(new HttpResponseEncoder());
p.addLast(new FrontendHandler(...));

我的FrontendHandler 扩展了SimpleChannelInboundHandler<HttpRequest>,所以它有一个

// Start reading as soon as a request comes in...
public void channelActive(ChannelHandlerContext ctx) {
    ctx.read();
}

还有一个

protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) {
    // copy request, fix headers, forward to backend server
}

如果收到大于 1024 字节的请求(例如,它有一些 cookie),服务器就会挂起。经过反复试验,我发现如果我在处理程序上设置ChannelOption.AUTO_READ,一切正常,所以看起来我的旧代码在某处缺少ctx.read() 调用,但我不知道在哪里。如果我做类似的事情

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

然后我在 channelRead0 中得到异常,这似乎是由于处理仍然不完整的 http 请求造成的,这违背了使用请求解码器/对象聚合器的目的。我错过了什么?

【问题讨论】:

标签: java http netty reverse-proxy


【解决方案1】:

我不知道 HttpObjectAggregator 是否可以处理分块消息。您可以尝试使用 HttpChunkAggregator,例如:

    pipeline.addLast("decoder", new HttpRequestDecoder(4096, 4096, 100*1024*1024));
    pipeline.addLast("aggregator", new HttpChunkAggregator(100*1024*1024));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("hndlr", new FrontendHandler(...));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2020-09-22
    • 1970-01-01
    • 2014-08-23
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多