我正在尝试使用 Netty 4.1 编写高性能反向代理服务器。 我的代码基于 Feng-Zihao/protox 的 Java 改编版和 Netty Proxy Example .
我首先在处理 100-CONTINUE 时遇到了一些问题,但将 HttpObjectAggregator
添加到我的管道中有点解决了这个问题。
serverBootstrap
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
ch.pipeline().addLast(new HttpRequestDecoder());
ch.pipeline().addLast(new HttpResponseEncoder());
ch.pipeline().addLast(new HttpObjectAggregator(1048576));
ch.pipeline().addLast(new FrontendHandler());
}
})
// .option(ChannelOption.SO_REUSEADDR, true)
// .option(ChannelOption.SO_BACKLOG, 128)
// .childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.AUTO_READ, false)
.bind(port).sync();
在客户端,请求无限期挂起。
问题是,AUTO_READ 处于 false
似乎阻止了 HttpObjectAggregator
完成他的工作,而我的 FrontendHandler
只接收到 channelActive
事件,但绝不是 channelRead
。
它seems though我需要它来确保我不会在读取和远程对等连接之间陷入某种竞争状态。
仅供引用,我最终的目标是根据需要读取完整 http 内容的过滤器(可能是我的 FrontendHandler 之前的新处理程序)选择转发或不转发请求。
我是不是漏掉了什么?
最佳答案
当您的出站 channel 激活时打开自动阅读,并让您的 FrontendHandler 在处理每条消息时将其关闭。然后在您准备好处理另一条消息时再次打开它。
这将使 HttpObjectAggregator 继续读取所需数量的消息以创建 FullHttpMessage,然后在 FrontendHandler 正在处理或等待某些客户端写入以调用监听器时停止向其发送消息。
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.channel().config().setAutoRead(false);
...
// This call should probably be in some event listener
ctx.channel().config().setAutoRead(true);
关于java - Netty过滤反向代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38663214/