消息队列工具类(MSMQ)
所要做的是简化msmq的调用代码以及做到可替代性,实现后,调用消息队列代码变为如下所示:
QueueService srv = QueueService.Instance(); //检查存储DTO1的队列是否存在,如不存在则自动建立 srv.Prepare<DTO1>(); //发送类型为DTO1的消息 srv.Send<DTO1>(new DTO1() { p1="1", p2="2" }); //发送类型为DTO1的消息,并且将发送的消息Id保存到msgId变量中 string msgId=srv.Send<DTO1>(new DTO1() { p1 = "1", p2 = "2" }); //接收末尾消息 DTO1 msg = srv.Receive<DTO1>(); //接收末尾消息,并且将这个消息Id保存在msgId变量中 DTO1 msg = srv.Receive<DTO1>(ref msgId); //发送回复消息,并且指定这个回复消息是特定消息ID所专有的回复消息 srv.SendResponse<DTO1>(msg, msgId); //接收特定消息ID的回复消息 msg=srv.ReceiveResponse<DTO1>(msgId);
主要的地方有2个:
- msmq消息大小限制的突破(4M突破)
- 泛型T对象的序列化、反序列化
突破大小限制
- 如果大小在4M内,则直接msmq封装(MessageLocation=InQueue)
- 如果在4M外,则通过网络共享文件来封装(MessageLocation=InNetwork)
泛型T对象的序列化、反序列化
- 固定住所要传递的对象类型为MessageWrapper
- 在MessageWrapper内部嵌入用户想要传递的其他对象以及相应的type、module名,这样MessageWrapper就能进行自动xml化以及反xml化了
MessageWrapper代码如下:
public class MessageWrapper { private ShareFileBroker fileBroker; public MessageWrapper() { PersistenceType = MessageLocation.InQueue; fileBroker = new ShareFileBroker(FileService.FileService.Instance()); } public string RealObjectType { get; set; } public string RealObjectModule { get; set; } public string RealObjectXml { get; set; } public string NetworkLocation { get; set; } public MessageLocation PersistenceType { get; set; } public void Inject<T>(T obj) { this.RealObjectType = typeof(T).FullName; this.RealObjectModule = typeof(T).Module.Name; string xml = SerializeUtils.Serialize2XML(typeof(T), obj); SaveXML(xml); } public T Extract<T>() { Assembly assembly = AppDomain.CurrentDomain.Load(this.RealObjectModule.TrimEnd(".dll".ToCharArray())); Type type = assembly.GetType(this.RealObjectType); string xml = GetXML(); return (T)SerializeUtils.DeserializeFromXML(type, xml); } private string GetXML() { string xml = ""; if (this.PersistenceType == MessageLocation.InQueue) xml = this.RealObjectXml; else if (this.PersistenceType == MessageLocation.InNetwork) xml = fileBroker.GetContentAndDelete(this.NetworkLocation); return xml; } private void SaveXML(string xml) { if (xml.Length > QueueConfiguration.QueueConfiguration.MaxQueueBodyLength) { this.NetworkLocation = fileBroker.Save(xml); this.PersistenceType = MessageLocation.InNetwork; } else { this.RealObjectXml = xml; this.PersistenceType = MessageLocation.InQueue; } } }
代码比较简单,就不介绍了。
自省推动进步,视野决定未来。
心怀远大理想。
为了家庭幸福而努力。
商业合作请看此处:https://www.magicube.ai
心怀远大理想。
为了家庭幸福而努力。
商业合作请看此处:https://www.magicube.ai
分类:
A2D Framework
标签:
msmq, QueueService
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何正确实现一个 BackgroundService
· 抽象与性能:从 LINQ 看现代 .NET 的优化之道
· AI 时代,为什么我们还有必要写博客?
· 行业思考:不是前端不行,是只会前端不行
· C#高级GDI+实战:从零开发一个流程图
· 记一次酣畅淋漓的js逆向
· 一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
· 上周热点回顾(7.28-8.3)
· Trae Plus 让没有编程基础的女朋友也用上了 AI Coding
· 架构师必备:实时对账与离线对账