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