WS+MQ+WCF+EF(Code First)

前言


       有段時間沒有更新博文了,一直在忙工做不多有時間靜下心來繼續研究點東西,說來也慚愧,歸咎緣由最主要的仍是由於懶惰。空想也是無論用的,有時候不少想法被扼殺到了搖籃裏,還沒開始作就放棄了,這是多數人會有的惡習,世界上最不缺乏的就是空想家,而是實踐者,有句俗話說的好不怕千招會,只怕一招絕,能踏踏實實作好一件事的人才是人生的贏家。另外在平時也有研究過不少有趣的技術,但每每是沒有研究到最後,只是研究瞭如何使用它,而後想要寫成文章就是很危險的事情,若是對某項技術研究的並不通透,這時候發表看法的話這樣只會害人,不會幫助人,要知道只知其一;不知其二最後害的會是本身。數據庫


1、架構淺析


      上文是寫給本身的由於發現本身最近有懶惰的惡習,因此作一下小小的反省,好了言歸正傳。上文討論了在分佈式開發時會用的基本的技術,其中包括微軟的WCF、Windows Service、Message Queue等,其中的Message Queue主要是討論了微軟的MQ,由於筆者如今是一名.net的程序猿,因此從最基本的微軟MQ開始詳細討論了MQ的使用方法。在有了前幾篇的技術基礎以後就能夠來看這篇文章了。
該篇文章將會使用前幾篇文章討論到的技術來搭一套小的框架,主要是實現Application(電腦或者移動端)和Web Service之間互相的通訊,中間的消息中介服務使用上文討論到的MQ來實現,具體的架構以下圖所示:
 
          關於上圖的實現,本例中的Application只是使用了Computer端的WPF來作的一個小的應用,消息隊列方是使用微軟的Message Queue來開發,Server Service開發的是Windows Service,遠程端的Web Service使用WCF來作的開發。具體開發的代碼將會在下文中詳細討論。
         Note:這種架構下近端的實體、遠程端的實體、WebService的實體以及數據契約的結構必須保持一致,這樣在開發時能夠避免寫不少轉換的中間代碼。

2、架構代碼


  2.1 近端App


        應用程序端作的是簡單的WPF應用程序,模擬了近端應用程序在執行完成後發送的消息信息到消息隊列中,本例中的消息隊列存儲的是xml格式的對象信息,因此在發送消息對象時須要首先指定消息隊列中信息的存儲方式,具體的模擬代碼以下:編程

[csharp] view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Security;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using System.Messaging;  
  8. using System.Xml.Serialization;  
  9.   
  10. namespace MQSend  
  11. {  
  12.     public class SendMQ  
  13.     {  
  14.         public void Send()  
  15.         {  
  16.             MessageQueue mq = null;  
  17.             if (!MessageQueue.Exists(".\\private$\\MSMQ"))  
  18.             {  
  19.                 mq = MessageQueue.Create(".\\private$\\MSMQ");  
  20.             }  
  21.             else  
  22.             {  
  23.                 mq = new MessageQueue(".\\private$\\MSMQ");  
  24.             }  
  25.             mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(Student),typeof(Teacher) });  
  26.   
  27.             for (int i = 0; i < 6; i++)  
  28.             {  
  29.                 mq.Send(new Student(){Id =i,Age = "13",Name = "張三"+i.ToString(),  
  30.                                       Teachers = new List<Teacher>()  
  31.                                       {  
  32.                                           new Teacher() { Id = 2,   
  33.                                               Name = "李老師"+i.ToString() }  
  34.                                       }  
  35.                 });  
  36.             }  
  37.             mq.Close();  
  38.         }  
  39.     }  
  40.   
  41.     [Serializable]  
  42.     public class Student  
  43.     {  
  44.         public int Id { getset; }  
  45.         public string Name { getset; }  
  46.         public string Age { getset; }  
  47.         public List<Teacher> Teachers { getset; }   
  48.   
  49.     }  
  50.     [Serializable]  
  51.     public class Teacher  
  52.     {  
  53.         public int Id { getset; }  
  54.         public string Name { getset; }  
  55.         public List<Student> Students { getset; }  
  56.     }  
  57.   
  58. }  

        Note:上面的代碼實體對象Student和Teacher存在多對多的關係,這種關係在序列化時每每會出現循環引用的問題,由於序列化其實是一種屬性的遍歷,會沿着對象一直向下循環序列化,因此在編程的時候必定要注意循環應用的
問題。
        Note:另外在引用屬性集合時不要聲明接口類型的集合,由於在發送消息隊列進行序列化時不容許聲明接口類型的集合,不然會發生相似於「XX是接口,所以沒法將其序列化。」的問題。
        運行該應用程序後,消息會被髮送到本機的消息隊列中,具體的消息示意圖以下:


   2.2 遠程端Server Service


        遠程端的Service本例開發的是Windows的服務,由於服務自開機以後能夠時刻的在運行,也就是說能夠時刻的獲取消息隊列中的消息,而後調用遠程端的Web Service對消息進行處理。因爲近端的消息發送的內容是xml序列化後的對象,因此在遠程端server在操做消息對象時須要將對象首先反序列化爲Service的實體對象(這裏的實體對象是指Web Service的實體對象),而後對實體對象作全部的操做。

        另外在開發Service的時候最好中間能夠記錄Service的運行過程,也就是將Service的運行過程記錄到日誌文件中,由於Service在運行過程當中很容易出現問題,在出現問題時將問題的內容記錄到日誌文件中,這樣可以較快的找到並修復問題。

        每一個Service都會有不少事件,其中使用最多的就是Service的開啓事件OnStart和結束事件OnStop,該例中在這兩個事件中分別添加了日誌記錄的功能,也就是在服務開啓和關閉時都會將服務的運行情況寫入日誌。另外在該服務中添加了一個Timer控件,該控件的Interval時間設置爲1000ms,這樣能夠實時的請求消息,而後對消息作操做,並保存日誌信息。
         項目結構以下圖所示,項目中添加了系統的WebService,併爲該WebService添加了具體的代理類MQServiceClient以及工具類FileOperate。
架構


          Service的具體代碼以下所示:

[csharp] view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.Messaging;  
  9. using System.ServiceModel;  
  10. using System.ServiceProcess;  
  11. using System.Text;  
  12. using System.Threading;  
  13. using System.Threading.Tasks;  
  14. using DistributeService.MQService;  
  15.   
  16. namespace DistributeService  
  17. {  
  18.     public partial class Service1 : ServiceBase  
  19.     {  
  20.         public Service1()  
  21.         {  
  22.             InitializeComponent();  
  23.         }  
  24.   
  25.         private ServiceHost host;  
  26.         private FileOperate fileOperate  
  27.         {  
  28.             get  
  29.             {  
  30.                 return FileOperate.GetFileOperate();  
  31.             }  
  32.         }  
  33.   
  34.         protected override void OnStart(string[] args)  
  35.         {  
  36.             try  
  37.             {  
  38.                 var str = "▌▌▌▌▌▌▌MQService start at " + DateTime.Now.ToString() + "▌▌▌▌▌▌▌\r\n";  
  39.                 fileOperate.WriteText(str, fileOperate.FileS);  
  40.             }  
  41.             catch (Exception ex)  
  42.             {  
  43.                 fileOperate.WriteText(ex.Message, fileOperate.FileS);  
  44.                 throw;  
  45.             }  
  46.               
  47.         }  
  48.   
  49.         protected override void OnStop()  
  50.         {  
  51.             Thread.Sleep(30000);  
  52.             var str = "▌▌▌▌▌▌▌MQService stop at " + DateTime.Now.ToString() + "▌▌▌▌▌▌▌\r\n"; ;  
  53.             fileOperate.WriteText(str,fileOperate.FileS);  
  54.   
  55.             if (this.host!=null)  
  56.             {  
  57.                 this.host.Close();  
  58.             }  
  59.         }  
  60.   
  61.         private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)  
  62.         {  
  63.             MessageQueue mq = null;  
  64.             if (MessageQueue.Exists(".\\private$\\MSMQ"))  
  65.             {  
  66.                 mq = new MessageQueue(".\\private$\\MSMQ");  
  67.                 try  
  68.                 {  
  69.                     mq.Formatter = new XmlMessageFormatter(new Type[] {typeof (Student)});  
  70.                     var me = mq.Receive();  
  71.                     var stu = me.Body;  
  72.   
  73.                     fileOperate.WriteText(stu.ToString() + "\r\n", fileOperate.FileM);  
  74.   
  75.                     var client = new MQHandlerClient();//.GetMqHandlerService();  
  76.                     client.Add((Student) stu);  
  77.                     client.Close();  
  78.                 }  
  79.                 catch (Exception ex)  
  80.                 {  
  81.                     fileOperate.WriteText(ex.ToString() + "\r\n", fileOperate.FileM);  
  82.                     throw;  
  83.                 }  
  84.                 finally  
  85.                 {  
  86.                     mq.Close();  
  87.                 }  
  88.   
  89.             }  
  90.               
  91.         }  
  92.     }  
  93. }  

      其中的 WebSerivceClient 的代碼以下所示:

[csharp] view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Management.Instrumentation;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using DistributeService.MQService;  
  8.   
  9. namespace DistributeService  
  10. {  
  11.     public class MQServiceClient  
  12.     {  
  13.         private static MQHandlerClient instance;  
  14.         private static object _object = new object();  
  15.   
  16.         private MQServiceClient()  
  17.         {  
  18.         }  
  19.   
  20.         public static MQHandlerClient GetMqHandlerService()  
  21.         {  
  22.             if (instance == null)  
  23.             {  
  24.                 lock (_object)  
  25.                 {  
  26.                     if (instance==null)  
  27.                     {  
  28.                         instance=new MQHandlerClient();  
  29.                     }  
  30.                 }  
  31.             }  
  32.   
  33.             return instance;  
  34.         }  
  35.   
  36.         ~MQServiceClient()  
  37.         {  
  38.             if (instance!=null)  
  39.             {  
  40.                 instance.Close();  
  41.                 instance.Abort();  
  42.             }  
  43.         }  
  44.     }  
  45. }  

         Note:這裏的代碼主要是作的消息處理,可是每每會出現錯誤,因此要記錄運行日誌,推薦使用開源的log4net或者Nlog,可是本例中是本身將堆棧信息寫入到文本文件當中,能夠方便查看。app


   2.3 遠程端Web Service

         遠程端Web Service公開了對消息的處理接口,主要是作的DB的增刪改查的操做。該例的Web Service使用的是WCF來開發的,後臺使用了EF 的Code First做爲系統的ORM框架,並使用FluentAPI來搭建了系統的映射部分,系統對外公佈了數據庫的增刪改查接口,具體的結構圖以下所示:
框架

         整個遠程端的Web Service爲其它端提供了數據的操做,其中的WCF在部署到host後對外公開對數據庫的CRUD操做接口,向下的DAL層封裝了數據庫的上下文(DbContext)以及數據庫的表實體,DAL層實體對象到數據庫的映射規則被封裝到了Mapping層中,該層的映射使用的是FluentAPI來實現的,最終對數據庫的操做是EF框架作的操做。接下來將會展現下幾個主要層的代碼。

    2.3.1  WCF層增刪改查

        下面的代碼是使用WCF來開發的Service,該Service在建立客戶端對象時會同時建立數據庫的一個上下文對象,最後將數據同步到Context中,由EF管理並同步到DB中。

[csharp] view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using DAL;  
  4. using Entitys;  
  5.   
  6. namespace DistributeWCF  
  7. {  
  8.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MQHandler" in code, svc and config file together.  
  9.     // NOTE: In order to launch WCF Test Client for testing this service, please select MQHandler.svc or MQHandler.svc.cs at the Solution Explorer and start debugging.  
  10.     public class MQHandler: IMQHandler  
  11.     {  
  12.         private TestContext context;  
  13.         public MQHandler()  
  14.         {  
  15.             this.context=new TestContext();  
  16.         }  
  17.   
  18.         public bool Add(Student stu)  
  19.         {  
  20.             this.context.Students.Add(new Entitys.Student(){Name = stu.Name,Teachers = new List<Entitys.Teacher>()});  
  21.             this.context.SaveChanges();  
  22.             return true;  
  23.         }  
  24.   
  25.         public bool Delete(int stuId)  
  26.         {  
  27.             var stu = this.context.Students.Find(new {stuId});  
  28.             this.context.Students.Remove(stu);  
  29.             this.context.SaveChanges();  
  30.             return true;  
  31.         }  
  32.   
  33.         public bool Update(Student stu) { return true; }  
  34.   
  35.         public List<Student> FindAll()  
  36.         {  
  37.             var lists = this.context.Students.SqlQuery("select * from student");  
  38.             var liststu = new List<Student>();  
  39.             foreach (var student in lists)  
  40.             {  
  41.                 var stu = new Student();  
  42.                 stu.StudentId = student.Id;  
  43.                 stu.Name = student.Name;  
  44.                 stu.Sex = student.Age;  
  45.                 stu.Teachers = new List<Teacher>();  
  46.                 foreach (var teacher in student.Teachers)  
  47.                 {  
  48.                     stu.Teachers.Add(new Teacher()  
  49.                     {  
  50.                         Id = teacher.Id,  
  51.                         Name = teacher.Name,  
  52.                     });  
  53.                 }  
  54.             }  
  55.             return liststu;  
  56.         }  
  57.     }  
  58.   
  59.       
  60. }  

    2.3.2 Fluent API的Mapping映射代碼

        該例使用的是Fluent API來作的映射,由於這種映射在修改時會很是的方便,而且在開發時控制對象關係編譯的過程,因此使用此種方法映射功能,該種映射很是的簡單,只要熟悉映射的規則就能夠很容易操做。以下代碼演示了該例中學生和老師的多對多關係之間的映射。
        對應的Teacher的Entity以及Mapping代碼以下:

[csharp] view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. using System.Data.Entity.ModelConfiguration;  
  2. using Entitys;  
  3. namespace Mapping  
  4. {  
  5.     public class TeacherMapping:EntityTypeConfiguration<Teacher>  
  6.     {  
  7.         public TeacherMapping()  
  8.         {  
  9.             this.ToTable("Teacher");  
  10.             this.HasKey(x => x.Id);  
  11.             this.Property(x => x.Id).HasColumnName("Id");  
  12.             this.Property(x => x.Name);  
  13.             this.HasMany(x=>x.Students)  
  14.                 .WithMany(x=>x.Teachers)  
  15.                 .Map(x => x.ToTable("StuTeahcer").MapLeftKey("TeacherId")  
  16.                     .MapRightKey("StudentId")  
  17.                     );  
  18.         }  
  19.     }  
  20.   
  21.     public class Teacher  
  22.     {  
  23.         public int Id { getset; }  
  24.         public string Name { getset; }  
  25.         public IList<Student> Students { getset; }   
  26.     }  
  27.       
  28. }  

    對應的StudentEntity以及Mapping代碼以下:分佈式

[csharp] view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity.ModelConfiguration;  
  3. using Entitys;  
  4. namespace Mapping  
  5. {  
  6.     public class StudentMapping:EntityTypeConfiguration<Student>  
  7.     {  
  8.         public StudentMapping()  
  9.         {  
  10.             this.ToTable("Student");  
  11.             this.HasKey(x => x.Id);  
  12.             this.Property(x => x.Id)  
  13.                 .HasColumnName("Id")  
  14.                 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)  
  15.                 .HasColumnType("int");  
  16.             this.Property(x => x.Name);  
  17.             this.Property(x => x.Age);  
  18.         }  
  19.     }  
  20.   
  21.     public class Student  
  22.     {  
  23.         public int Id { getset; }  
  24.         public string Name { getset; }  
  25.         public string Age { getset; }  
  26.         public IList<Teacher> Teachers { getset; }   
  27.     }  
  28.       
  29. }  

        Note:EF的實體到對象的映射有多種方式,最經常使用的是DataAnnotations數據註解以及Fluent API兩種方式來編寫映射。該例中的學生和老師屬於多對多的關係,在使用Fluent API添加映射的時候只須要在對象的一端添加相互之間的多對多關係,由於此種關係要生成中間表因此要使用ToTable來指定中間表的代表,以及使用MapLeftKey和MapRightKey指定表的主鍵。
        上面的代碼就是遠程端的主要代碼,在運行代碼後會在數據庫中添加對應的表結構,開發時很簡單,生成的數據庫的表結構以下圖所示:

結語


        由於本文只是提出了一種分佈式開發的方法,這種方法須要在項目中接受考驗才能評價架構的好壞,另外在開發時還須要作嚴格的管理,並統一編碼規範和驗收標準,還有不少須要注意的地方,本文提出的內容不必定所有正確,可是通過了筆者的測試,有什麼問題還請留言一塊探討。

版權聲明:本文爲博主原創文章,未經博主容許不得轉載。ide

相關文章
相關標籤/搜索