• 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()
        {
     
        }
    }
    作者:江振宇
    出处:http://jzywh.cnblogs.com
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    Java中常见数据结构:List与Map
    JAVA 双重检查锁定和延迟初始化
    Spring 读取配置文件(二)
    Spring 读取配置文件(一)
    Java配置文件读取和路径设置
    动态设置spring配置PropertyPlaceholderConfigurer location的路径
    MySQL 数据库备份种类以及经常使用备份工具汇总
    打印二叉树两个叶子节点间的路径
    读书报告之《改动代码的艺术》 (I)
    虚幻引擎自带的创建插件的插件
  • 原文地址:https://www.cnblogs.com/jzywh/p/2043666.html
Copyright © 2020-2023  润新知