消息隊列工具類(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;
            }
        }
    }

 代碼比較簡單,就不介紹了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM