SuperSocket 1.4系列文档(12) 命令过滤器(Command Filter)

SuperSocket的Command Filter功能类似于ASP.NET MVC中的Action Filter,你可以用它来截获Command的执行,在Command运行之前或之后运行Filter的代码。

Command Filter必须继承自Attribute类CommandFilterAttribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public abstract class CommandFilterAttribute : Attribute
{
    public abstract void OnCommandExecuting(IAppSession session, ICommand command);
 
    public abstract void OnCommandExecuted(IAppSession session, ICommand command);
}

你的CommandFilter有两个方法需要实现,

OnCommandExecuting: 此方法在Command执行之前被调用;

OnCommandExecuted: 此方法在Command执行之后被调用;

 

下面的代码定义了LogTimeCommandFilterAttribute这一Command Filter用于记录执行时间超过5秒的Command, 并通过Attribute的方式应用于QUERY这一Command:

public class LogTimeCommandFilterAttribute : CommandFilterAttribute
{
    public override void OnCommandExecuting(IAppSession session, ICommand command)
    {
        session.Items["StartTime"] = DateTime.Now;
    }
 
    public override void OnCommandExecuted(IAppSession session, ICommand command)
    {
        var startTime = session.Items.GetValue<DateTime>("StartTime");
        var ts = DateTime.Now.Subtract(startTime);
 
        if (ts.TotalSeconds > 5)
        {
            session.Logger.LogPerf(string.Format("A command '{0}' took {1} seconds!", command.Name, ts.ToString()));
        }
    }
}
 
[LogTimeCommandFilter]
public class QUERY : StringCommandBase<TestSession>
{
    public override void ExecuteCommand(TestSession session, StringCommandInfo commandData)
    {
        //Your code
    }
}

如果你想把某个Command Filter应用于所有的Command, 你只需将Command Filter的Attribute加到你的              AppServer类上面,如下代码:

[LogTimeCommandFilter]
public class TestServer : AppServer<TestSession>
{
    public TestServer()
        : base()
    {
 
    }
}
posted @ 2011-05-11 21:16  江大渔  阅读(2826)  评论(3编辑  收藏  举报