Netty - 跳过管道中的其余处理程序

yee*_*123 2 asynchronous netty

我目前正在使用 Netty 4.0,如果这很重要的话,但无论如何..

我有一个这样编写的处理程序,以便我想根据 URI 过滤掉请求:

public class URIFilterHandler extends SimpleChannelInboundHandler<HttpRequest> {

public void channelRead0(ChannelHandlerContext ctx, HttpRequest req) {
    String uri = req.uri();

    if (uri.contains("abcde")) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        ctx.writeAndFlush(response);
        // HERE IS WHERE I WANT TO SKIP REST OF THE HANDLERS

    } else {
        ctx.fireChannelRead(req);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

然后这是我的管道

public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();

        p.addLast(new HttpRequestDecoder());
        p.addLast(new HttpResponseEncoder());
        p.addLast(new URIFilterHandler());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new RequestHandler());

    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了以下操作,但它似乎从管道中永久删除了这些处理程序,而不仅仅是针对一个请求。

       ctx.pipeline().remove(HttpObjectAggregator.class);
       ctx.pipeline().remove(RequestHandler.class;)
Run Code Online (Sandbox Code Playgroud)

我尝试使用 ctx.channel().close() 和 ctx.fireChannelInactive() 无济于事。它似乎仍然将请求传递到下一个处理程序(在本例中为 HttpObjectAggregator)。我认为这可能是由于 close() 和 fireChannelInactive() 异步造成的?

编辑:我遇到的问题似乎是我发回了 DefaultHttpResponse。当我发回 DefaultFullHttpResponse 时,请求永远不会挂起。

Pri*_*rim 5

要跳过其余的处理程序,只需什么都不做。要继续使用下一个处理程序、初始对象或彼此之间处理数据,请调用ctx.fireChannelRead( object )

处理引用计数对象。SimpleChannelInboundHandler默认情况下释放输入(取决于构造函数参数)。如果您决定将其解雇给下一个处理程序,则必须调用ReferenceCountUtil.retain(Object)。请参阅此处的文档:http ://netty.io/wiki/reference-counted-objects.html

此外,我认为您应该将HttpObjectAggregator处理程序放在管道上您自己的处理程序之前,并使您的处理程序捕获FullHttpRequest. HttpObjectAggregator为您处理所有 http 块并放入管道 a FullHttpRequest。就您而言,这可能很有趣,因为如果您忽略一个块,那么您如何处理已经聚合在管道上的其他块?我猜如果你什么都不做,你可能会抛出 DecoderException 。

  • ReferenceCountUtil.retain(Object) 很有帮助,谢谢! (3认同)