首页 技术 正文
技术 2022年11月21日
0 收藏 965 点赞 3,035 浏览 5730 个字
如何指定Business Event和Command之间的关系?

既然是基于惯例优先原则,那么我们首先需要定义一个惯例:

1.调度事件和调度处理器之间是一对多关系(多对多的话,相信你看完了以后应该会知道怎么改的)。

2.所有业务事件(Event)要以调度事件为基类,业务指令(Command)的调度处理器特性需要指定可处理的调度事件。

     /// <summary>
/// 调度事件
/// </summary>
public class DispatchEvent
{ }
      /// <summary>
/// 调度处理器
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class DispatchHandlerAttribute : Attribute
{
/// <summary>
/// 观察的调度事件类型
/// </summary>
public Type ObservedDispatchEventType { get; set; } /// <summary>
/// 调度实例
/// </summary>
public object DispatchInstance { get; set; } /// <summary>
/// 动作方法信息
/// </summary>
public MethodInfo ActionMethodInfo { get; set; } /// <summary>
/// 构造函数
/// </summary>
/// <param name="observedDispatchEventType">观察的调度事件类型</param>
public DispatchHandlerAttribute(Type observedDispatchEventType)
{
this.ObservedDispatchEventType = observedDispatchEventType;
}
}
如何创建一个业务事件?

我们基于获取AccessToken作为第一个业务事件,先创建一个获取AccessToken的事件

当然,具体交互微信细节就省略了,如果感兴趣可留言,看多少人关注我考虑下是否把微信相关的东西也一起加进来

      /// <summary>
/// 获取微信交互接口凭证事件
/// </summary>
public class GetAccessTokenEvent : DispatchEvent
{
/// <summary>
/// 微信交互接口凭证信息
/// </summary>
public AccessTokenInfo AccessTokenInfo { get; set; }
}

此时有人会问了,不是获取AccessToken吗?传的不应该是一些APPID、APPSecurity之类的吗,为什么是AccessTokenInfo?
嗯,伟大的值类型和引用类型就派上用场了,因为Event会作为参数传递给Command,由Command自行填充。既然GetAccessTokenEvent是引用类型,那么在Command内修改AccessToken是不需要返回一个新的Event或者对象,直接在Event内的AccessTokenInfo上修改就好了,调用者就会得到他想要的东西。

虽然这只是个小知识点,大多数人都知道,但是有人喜欢用,因为可以偷懒。

有人不喜欢,觉得这样会让一些人不明白内部到底做了些什么,调用者该如何使用这个事件。

具体怎么做,因人而异吧,这不是重点,关键是一开始就提了:惯例优先原则。而这,不就是一个惯例吗? ^_^

如何创建一个业务指令,与上一个业务事件关联起来?

这里有个小小的业务,就是AccessToken获取后有失效时间,过了要重新获取。又不能每次都获取,因为又有获取次数限制。

为了处理这个问题,我做了个自动更新缓存类,这个在AccessTokenCommand的静态构造函数里设置一次获取逻辑。

之后其他功能在使用到以后都是从缓存里拿的。那么这个稍微有点逻辑的业务我们看看Command该怎么写。

     /// <summary>
/// 微信交互接口凭证命令
/// </summary>
public class AccessTokenCommand
{
#region 静态构造函数 static AccessTokenCommand()
{
AutoUpdateCache.Add(CacheKeySet.AccessToken.ToString(), new AutoUpdateItem()
{
UpdateValue = (AutoUpdateItem autoUpdateItem) =>
{
var accessTokenInfo = CommandHelper.GetWeChatResponseObject<AccessTokenInfo>(new AccessTokenCommandRequest()); autoUpdateItem.ExpiredSeconds = accessTokenInfo.ExpiresIn - ;//预留过期时效,防止提前过期
autoUpdateItem.Value = accessTokenInfo;
}
});
} #endregion /// <summary>
/// 获取微信交互接口凭证
/// </summary>
/// <param name="e"></param>
[DispatchHandler(typeof(GetAccessTokenEvent))]
public void GetAccessToken(GetAccessTokenEvent e)
{
e.AccessTokenInfo = AutoUpdateCache.GetValue<AccessTokenInfo>(CacheKeySet.AccessToken.ToString());
}
}

从 GetAccessToken 这个方法我们可以看出他有几个地方是需要注意的。
1.有一个特性 [DispatchHandler(typeof(GetAccessTokenEvent))] ,这个意思是标识当前方法是一个调度处理器,所处理的事件是 GetAccessTokenEvent

2.没有任何返回值

3.直接把AccessTokenInfo赋值到 GetAccessTokenEvent 这个传入参数里

如何把Event和Command关联起来呢?

我先声明,我本人是不太喜欢写一坨坨的配置文件的,虽然配置更灵活,但配置太多反而维护起来极度不方便。

那么,不使用配置就相当于要有一定的规则,否则我们是梳理不出来如何自动创建关联关系。我们就叫他“调度器”好了。

这个调度器应该具备以下几个功能:

1.解析任意一个程序集

2.扫描所有的DispatchHandler,即调度处理器

3.缓存调度关系网,降低反射带来的性能损耗

4.传一个调度事件参数,自行调用所有的调度处理器

       /// <summary>
/// 调度器
/// </summary>
public class Dispatcher
{
/// <summary>
/// 调度关系网
/// </summary>
private static Dictionary<Type, List<DispatchHandlerAttribute>> _dicDispatchRelativeNetwork = new Dictionary<Type, List<DispatchHandlerAttribute>>(); /// <summary>
/// 建立调度关系网
/// </summary>
/// <param name="assembly"></param>
public static void BuildDispatchRelationship(Assembly assembly)
{
Logger.Info("调度器:开始建立调度关系网..."); var types = assembly.GetTypes(); foreach (var type in types)
{
var methods = type.GetMethods(); foreach (var method in methods)
{
var attribute = method.GetCustomAttributes(typeof(DispatchHandlerAttribute), true).FirstOrDefault();
if (attribute != null)
{
CheckParameterRule(method); var handler = attribute as DispatchHandlerAttribute;
handler.DispatchInstance = Activator.CreateInstance(type);
handler.ActionMethodInfo = method;
AddDispatchRelation(handler);
}
}
}
} /// <summary>
/// 添加调度关系
/// </summary>
/// <param name="handler">调度处理器</param>
private static void AddDispatchRelation(DispatchHandlerAttribute handler)
{
var eventType = handler.ObservedDispatchEventType; if (!_dicDispatchRelativeNetwork.ContainsKey(eventType))
{
_dicDispatchRelativeNetwork.Add(eventType, new List<DispatchHandler>());
} _dicDispatchRelativeNetwork[eventType].Add(handler); Logger.Info(string.Format("调度器:建立新的关系网 [{0}]-[{1}.{2}]", eventType.Name, handler.DispatchInstance.GetType().Name, handler.ActionMethodInfo.Name));
} /// <summary>
/// 检查参数规则
/// </summary>
/// <param name="method"></param>
private static void CheckParameterRule(MethodInfo method)
{
var parameters = method.GetParameters();
if (parameters == null ||
parameters.Length != ||
(!parameters.FirstOrDefault().ParameterType.Equals(typeof(DispatchEvent)) &&
!parameters.FirstOrDefault().ParameterType.BaseType.Equals(typeof(DispatchEvent))
))
{
throw new Exception(string.Format("DispatchHandler - [{0}]的参数必须是只有一个且继承自DispatchEvent", method.Name));
}
} /// <summary>
/// 激活事件
/// </summary>
/// <param name="dispatchEvent">调度事件</param>
public static void ActiveEvent(DispatchEvent dispatchEvent)
{
var type = dispatchEvent.GetType(); if (!_dicDispatchRelativeNetwork.ContainsKey(type))
{
Logger.Error(string.Format("调度器:当前事件[{0}]没有找到绑定的Handler", type.FullName));
return;
} _dicDispatchRelativeNetwork[type].ForEach(action =>
{
ActiveAction(action, dispatchEvent);
});
} private static void ActiveAction(DispatchHandlerAttribute action, DispatchEvent dispatchEvent)
{
try
{
action.ActionMethodInfo.Invoke(action.DispatchInstance, new object[] { dispatchEvent });
}
catch (Exception ex)
{
if (ex.InnerException != null && ex.InnerException.GetType().Equals(typeof(WCFLib.ExceptionExtension.GException)))
{
throw ex.InnerException;
}
else
{
throw;
}
}
}
}
如何激活Event?

创建一个事件,使用调度器激活事件,最后从事件中的属性获取你需要的返回值。

             var getAccessTokenEvent = new GetAccessTokenEvent();
Dispatcher.ActiveEvent(getAccessTokenEvent);
var accessTokenInfo = getAccessTokenEvent.AccessTokenInfo;

此时又有人会问了,为什么不直接用  new AccessTokenCommand().GetAccessToken(new GetAccessTokenEvent());
因为Event所在类库是没有添加Command引用的。通过调度者动态加载的。

那么问题又来了,这么劳民伤财为的是什么?

卖个关子,下篇继续造轮子。 ^_^

别急别急,还没完

这年头不应该有图有真相吗?

【轮子狂魔】打造简易无配置的IoC

感谢所有耐心看完的人,欢迎提出你们的宝贵意见和批评。让我们一起进步吧。

下一篇预告:【轮子狂魔】调度器的扩展能力

如果你喜欢这篇博文,或者期待下一篇博文,麻烦点下推荐,你们的支持是我的动力 ^_^

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860