Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically changing netty pipeline

Tags:

netty

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

like image 492
Tanima Saini Avatar asked Dec 12 '22 00:12

Tanima Saini


1 Answers

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;
}
like image 140
trustin Avatar answered Jan 22 '23 05:01

trustin