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 @   江大渔  阅读(2850)  评论(3编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示