dynamically changing netty pipeline

倖福魔咒の 提交于 2021-02-19 02:35:30

问题


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
                 );

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. 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?

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

  3. Is there any other way to do this?

Thanks & Regards,

Tanima


回答1:


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);
        } ...
    }
}

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;
}


来源:https://stackoverflow.com/questions/28804413/dynamically-changing-netty-pipeline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!