Netty过滤反向代理

时间:2016-07-29 16:10:27

标签: java proxy netty reverse-proxy

我正在尝试使用Netty 4.1编写高性能反向代理服务器。 我的代码基于Feng-Zihao/protoxNetty Proxy Example的Java改编。

我首先在处理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之前的新处理程序)选择转发或不转发请求。

我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:3)

当出站通道变为活动状态时打开自动读取,并在处理每条消息时让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);
相关问题