Fork me on GitHub

SuperSocket 1.5 Documentation译文 11 ----- 命令过滤器

SuperSocket的命令过滤功能看起来像ASP.NET MVC中的行为过滤器, 你可以用它来拦截执行命令, 命令过滤器将在命令执行前或之后被调用.

命令过滤器类必须从属性CommandFilterAttribute继承:

/// <summary>
/// 命令过滤器属性
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public abstract class CommandFilterAttribute : Attribute
{
    /// <summary>
    /// 获取或设置执行顺序.
    /// </summary>
    /// <value>
    /// 顺序.
    /// </value>
    public int Order { get; set; }

    /// <summary>
    /// [命令执行前调用].
    /// </summary>
    /// <param name="commandContext">The command context.</param>
    public abstract void OnCommandExecuting(CommandExecutingContext commandContext);

    /// <summary>
    /// [命令执行后调用].
    /// </summary>
    /// <param name="commandContext">The command context.</param>
    public abstract void OnCommandExecuted(CommandExecutingContext commandContext);
}

有两种方法为您的命令来实现过滤器:

OnCommandExecuting: 这个方式在命令执行前被调用;

OnCommandExecuted: 这个方法在命令执行后被调用;

Order: 您还可以设置Order属性的命令过滤器来控制执行顺序

下面的代码定义的一个命令过滤LogTimeCommandFilter,记录执行时间超过5秒的命令,:

public class LogTimeCommandFilter : CommandFilterAttribute
{
    public override void OnCommandExecuting(CommandExecutingContext commandContext)
    {
        commandContext.Session.Items["StartTime"] = DateTime.Now;
    }

    public override void OnCommandExecuted(CommandExecutingContext commandContext)
    {
        var session = commandContext.Session;
        var startTime = session.Items.GetValue<DateTime>("StartTime");
        var ts = DateTime.Now.Subtract(startTime);

        if (ts.TotalSeconds > 5 && session.Logger.IsInfoEnabled)
        {
            session.Logger.InfoFormat("A command '{0}' took {1} seconds!", commandContext.CurrentCommand.Name, ts.ToString());
        }
    }
}

然后应用命令过滤器“QUERY命令”添加属性:

[LogTimeCommandFilter]
public class QUERY : StringCommandBase<TestSession>
{
    public override void ExecuteCommand(TestSession session, StringCommandInfo commandData)
    {
        //Your code
    }
}

如果你想在所有命令中应用这个命令过滤器, 你必须像这样添加命令过滤器属性到你的AppServer:

[LogTimeCommandFilter]
public class TestServer : AppServer<TestSession>
{

}

您还可以设置commandContext的Cancel属性为true,取消命令的执行:

public class LoggedInValidationFilter : CommandFilterAttribute
{
    public override void OnCommandExecuting(CommandExecutingContext commandContext)
    {
        var session = commandContext.Session as MyAppSession;

        //If the session is not logged in, cancel the executing of the command
        if (!session.IsLoggedIn)
            commandContext.Cancel = true;
    }

    public override void OnCommandExecuted(CommandExecutingContext commandContext)
    {

    }
}
posted @ 2013-03-19 22:44  逗豆豆  阅读(280)  评论(0编辑  收藏  举报