动态改变 netty 管道 [英] dynamically changing netty pipeline

查看:51
本文介绍了动态改变 netty 管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 netty 4.0.25Final 编写一个 netty HTTP 服务器.我需要根据 HTTP GET 请求中的一些参数在管道中添加各种处理程序.

I am using netty 4.0.25Final to write a netty HTTP server. I need to add various handlers in the pipeline depending upon some parameters in HTTP GET request.

pipeline.addLast(new HttpRequestDecoder(4096, 8192, 8192, false),
                 new HttpResponseEncoder(),
                 new HttpObjectAggregator(1048576),
                 decisionHandler
                 );

如果多个请求来自同一个连接,则使用相同的管道.Request1 可能需要 Handler1,Request2 可能需要 Handler2,Request3 可能需要 Handler3.假设请求以 Request1、Request2、Request3 的形式出现.Request1 将修改管道以添加 Handler1.

Same pipeline is used if multiple requests come from the same connection. Request1 may need Handler1, Request2 may need Handler2 and Request3 may need Handler3. Suppose requests are coming as Request1, Request2, Request3. Request1 would modify the pipeline to add Handler1.

  1. 在后续调用中,我们是否总是需要检查管道线是否已被修改,然后删除不需要的处理程序?然后添加处理该特定调用所需的所需处理程序?

  1. In subsequent calls do we always need to check if the pipleline is already modified, then remove the unwanted handlers? And then add the required handlers which are needed to handler that particular call?

或者我应该在转到下一个处理程序(fireChannelRead(对象))之前删除处理程序?它会影响性能吗?

Or should I remove the handler before going to the next handler (fireChannelRead(object))? Will it have performance impact?

有没有其他方法可以做到这一点?

Is there any other way to do this?

谢谢&问候,

谷马

推荐答案

动态操作管道是一项相对昂贵的操作.如果您尝试实现的只是一个简单的 switch-case,例如委托,您可以编写一个处理程序来执行此操作.例如:

Dynamically manipulating a pipeline is relatively an expensive operation. If what you are trying to implement is just a simple switch-case like delegation, you can write a handler that does that. For example:

public class SwitchCaseHandler extends ChannelInboundHandlerAdapter {

    private final ChannelInboundHandler handler1 = ...;
    private final ChannelInboundHandler handler2 = ...;
    private final ChannelInboundHandler handler3 = ...;
    ...

    @Override
    public void channelRead(ctx, msg) {
        if (isForHandler1(msg)) {
            handler1.channelRead(ctx, msg);
        } else if (isForHandler2(msg)) {
            handler2.channelRead(ctx, msg);
        } ...
    }
}

请注意,handler[1|2|3] 不需要是 ChannelInboundHandler.您可以定义一个非常简单的接口,如下所示:

Please note that handler[1|2|3] doesn't need to be a ChannelInboundHandler really. You could define a very simple interface like the following instead:

public interface ChannelMessageHandler {
    void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception;
}

这篇关于动态改变 netty 管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆