百寶箱演示WCF消息隊列解決方案
消息就是信息的來源,在WCF中消息隊列分為公共隊列、專用隊列、管理隊列、響應隊列四種,下面我們就簡單的分析一下WCF消息隊列吧。MessageQueue.Create參數是存放消息隊列的位置.這個基本就完成了創建和發送消息的主程序.下面我們來建立一個客戶端,來訪問消息隊列,獲取消息,同樣建立一個控制臺應用程序,添加引用和代碼:
- 1namespace MSMQClient
- class Program
- {
- static void Main(string[] args)
- {
- //Get public queue message
- if (MessageQueue.Exists(@".FrankMSMQ"))//判斷是否存在消息隊列
- {
- using(MessageQueue mq = new MessageQueue(@".FrankMSMQ"))//創建消息隊列對象
- {
- mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });//設置消息隊列的格式化器
- //mq.Send("Sample Message", ":Label");
- Message msg = mq.Receive();//從隊列接受消息
- Console.WriteLine("Received MSMQ Message is :{0}", msg.Body);//輸出消息
- }
- //Console.Read();
- }
- //Get private queue message
- if (MessageQueue.Exists(@".Private$FrankMSMQ"))//判斷私有消息是否存在
- {
- using (MessageQueue mq = new MessageQueue(@".Private$FrankMSMQ"))
- {
- mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });//設置消息隊列格式化器
- //mq.Send("Sample Message", ":Label");
- Message msg = mq.Receive();//接收消息
- Console.WriteLine("Received MSMQ Private Message is: {0}", msg.Body);//輸出消息
- }
- }
- Console.Read();
- }
- }
- }
#T#消息接收同樣需要實例化一個WCF消息隊列對象, using(MessageQueue mq = new MessageQueue(@".FrankMSMQ"))負責創建WCF消息隊列對象.其次 mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" })這行代碼負責設置消息隊列的格式化器,因為消息的傳遞過程中存在格式化的問題.我們接收消息的時候必須指定消息隊列的格式化屬性Formatter, 隊列才能接受消息。
XmlMessageFormatter的作用是進行消息的XML串行化.BinaryMessageFormatter則把消息格式化為二進制數據進行傳輸.ActiveXMessageFormatter把消息同樣進行二進制格式化,區別是可以使用COM讀取隊列中的消息.當然消息隊列還可以發送復雜的對象,前提是這個對象要可串行化,具體的格式取決與隊列的格式化器設置.此外消息隊列還支持事務隊列來確保消息只發送一次和發送的順序.最近在研究SOA,所以系統系統學習一下WCF及其相關的技術,以上就是這個消息隊列的基本的概念和簡單的編程實現.下一節是關于.Net Remoting的基礎知識和開發的文章.~