管道中的条件ExecutionHandler [英] Conditional ExecutionHandler in pipeline

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

问题描述

我正在开发的服务器根据从客户端收到的消息执行不同的任务,其中一些任务非常简单,需要很少的时间来执行,而其他的则可能需要一段时间.

将ExecutionHandler添加到管道中似乎是解决复杂任务的好方法,但我希望避免对简单任务进行线程化.

我的管道如下所示:

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

MessageEncoder返回一个Message对象(用于decode),该对象定义了所请求的任务.

是否有一种方法可以根据解码后的消息跳过执行处理程序?
这个问题可以概括为:有没有办法确定是否将使用下一个处理程序?

谢谢.

解决方案

您可以扩展它以覆盖其handlerUpstream()方法来拦截上游事件,并为MessageEvent s的消息符合您的条件.所有其他事件可由ExecutionHandler通过super.sendUpstream(e)处理.那就是:

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

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.

解决方案

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

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

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