詳解C#如何使用消息隊列MSMQ
最近項目用到消息隊列,找資料學(xué)習(xí)了下。把學(xué)習(xí)的結(jié)果 分享出來
首先說一下,消息隊列 (MSMQ Microsoft Message Queuing)是MS提供的服務(wù),也就是Windows操作系統(tǒng)的功能,并不是.Net提供的。
MSDN上的解釋如下:
Message Queuing (MSMQ) technology enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline.
Applications send messages to queues and read messages from queues.
The following illustration shows how a queue can hold messages that are generated by multiple sending applications and read by multiple receiving applications.
消息隊列(MSMQ)技術(shù)使得運行于不同時間的應(yīng)用程序能夠在各種各樣的網(wǎng)絡(luò)和可能暫時脫機的系統(tǒng)之間進行通信。
應(yīng)用程序?qū)⑾l(fā)送到隊列,并從隊列中讀取消息。
下圖演示了消息隊列如何保存由多個發(fā)送應(yīng)用程序生成的消息,并被多個接收應(yīng)用程序讀取。
消息一旦發(fā)送到隊列中,便會一直存在,即使發(fā)送的應(yīng)用程序已經(jīng)關(guān)閉。
MSMQ服務(wù)默認是關(guān)閉的,(Window7及以上操作系統(tǒng))按以下方式打開
1、打開運行,輸入"OptionalFeatures",鉤上Microsoft Message Queue(MSMQ)服務(wù)器。
(Windows Server 2008R2及以上)按以下方式打開
2、打開運行,輸入"appwiz.cpl",在任務(wù)列表中選擇“打開或關(guān)閉Windows功能”
然后在"添加角色"中選擇消息隊列
消息隊列分為以下幾種,每種隊列的路徑表示形式如下:
公用隊列 MachineName\QueueName
專用隊列 MachineName\Private$\QueueName
日記隊列 MachineName\QueueName\Journal$
計算機日記隊列 MachineName\Journal$
計算機死信隊列 MachineName\Deadletter$
計算機事務(wù)性死信隊列 MachineName\XactDeadletter$
這里的MachineName可以用 “."代替,代表當前計算機
需要先引用System.Messaging.dll
創(chuàng)建消息隊列
//消息隊列路徑 string path = ".\\Private$\\myQueue"; MessageQueue queue; //如果存在指定路徑的消息隊列 if(MessageQueue.Exists(path)) { //獲取這個消息隊列 queue = new MessageQueue(path); } else { //不存在,就創(chuàng)建一個新的,并獲取這個消息隊列對象 queue = MessageQueue.Create(path); }
發(fā)送字符串消息
System.Messaging.Message msg = new System.Messaging.Message(); //內(nèi)容 msg.Body = "Hello World"; //指定格式化程序 msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); queue.Send(msg);
發(fā)送消息的時候要指定格式化程序,如果不指定,格式化程序?qū)⒛J為XmlMessageFormatter(使用基于 XSD 架構(gòu)定義的 XML 格式來接收和發(fā)送消息。)
接收字符串消息
//接收到的消息對象 System.Messaging.Message msg = queue.Receive(); //指定格式化程序 msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); //接收到的內(nèi)容 string str = msg.Body.ToString();
發(fā)送二進制消息(如圖像)
引用 System.Drawing.dll
System.Drawing.Image image = System.Drawing.Bitmap.FromFile("a.jpg"); Message message = new Message(image, new BinaryMessageFormatter()); queue.Send(message);
接收二進制消息
System.Messaging.Message message = queue.Receive(); System.Drawing.Bitmap image= (System.Drawing.Bitmap)message.Body; 3image.Save("a.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
獲取消息隊列的消息的數(shù)量
int num = queue.GetAllMessages().Length;
清空消息隊列
queue.Purge();
以圖形化的方式查看消息隊列中的消息
運行輸入 compmgmt.msc,打開計算機管理,選擇[服務(wù)和應(yīng)用程序-消息隊列]。只要消息隊列中的消息沒有被接收,就可以在這里查看得到。
到此這篇關(guān)于詳解C#如何使用消息隊列MSMQ的文章就介紹到這了,更多相關(guān)C#消息隊列MSMQ內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c# 連接access數(shù)據(jù)庫config配置
c# 連接access數(shù)據(jù)庫config配置,需要的朋友可以參考一下2013-02-02C#中Override關(guān)鍵字和New關(guān)鍵字的用法詳解
這篇文章主要介紹了C#中Override關(guān)鍵字和New關(guān)鍵字的用法,需要的朋友可以參考下2016-01-01