Conditional ExecutionHandler in pipeline

时间秒杀一切 提交于 2019-12-24 08:07:53

问题


The server I'm developing has different tasks to perform based on messages received from clients, some tasks are very simple and require little time to perform, but other may take a while.

Adding an ExecutionHandler to the pipeline seems like a good solution for the complicated tasks but I would like to avoid threading simple tasks.

My pipeline looks like this:

pipeline.addLast("decoder", new MessageDecoder());
pipeline.addLast("encoder", new MessageEncoder());
pipeline.addLast("executor", this.executionHandler);
pipeline.addLast("handler", new ServerHandler(this.networkingListener));

Where MessageEncoder returns a Message object (for decode) which defines the requested task.

Is there a way to skip the execution handler based on the decoded message?
The question can be generalized to: is there a way to condition whether or not the next handler will be used?

Thanks.


回答1:


Instead of using ExecutionHandler as is, you can extend it to override its handlerUpstream() method to intercept the upstream events and call ctx.sendUpstream(e) for the MessageEvents whose message meets your criteria. All other events could be handled by the ExecutionHandler via super.sendUpstream(e). That is:

public class MyExecutionHandler extends ExecutionHandler {
    public void handleUpstream(ctx, evt) throws Exception {
        if (evt instanceof MessageEvent) {
            Object msg = ((MessageEvent) evt).getMessage();
            if (msg instanceof ExecutionSkippable) {
                ctx.sendUpstream(evt);
                return;
            }
        }

        super.handleUpstream(evt);
    }
    ...
}



回答2:


You can remove it (or add it on demand) from the pipeline inside your MessageDecoder before you send the message upstream. You can also check the message inside your executionHandler and just pass it upstream. In case you cannot modify these two files you can create another handler which removes executionHandler based on the message type.



来源:https://stackoverflow.com/questions/14593192/conditional-executionhandler-in-pipeline

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