最近项目用到消息队列,找资料学习了下。把学习的结果 分享出来服务器
首先说一下,消息队列 (MSMQ Microsoft Message Queuing)是MS提供的服务,也就是Windows操做系统的功能,并非.Net提供的。网络
MSDN上的解释以下:架构
Message Queuing (MSMQ) technology enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline.app
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.ui
消息队列(MSMQ)技术使得运行于不一样时间的应用程序可以在各类各样的网络和可能暂时脱机的系统之间进行通讯。spa
应用程序将消息发送到队列,并从队列中读取消息。操作系统
下图演示了消息队列如何保存由多个发送应用程序生成的消息,并被多个接收应用程序读取。3d
消息一旦发送到队列中,便会一直存在,即便发送的应用程序已经关闭。code
MSMQ服务默认是关闭的,(Window7及以上操做系统)按如下方式打开
一、打开运行,输入"OptionalFeatures",钩上Microsoft Message Queue(MSMQ)服务器。
(Windows Server 2008R2及以上)按如下方式打开
二、打开运行,输入"appwiz.cpl",在任务列表中选择“打开或关闭Windows功能”
而后在"添加角色"中选择消息队列
消息队列分为如下几种,每种队列的路径表示形式以下:
公用队列 MachineName\QueueName
专用队列 MachineName\Private$\QueueName
日记队列 MachineName\QueueName\Journal$
计算机日记队列 MachineName\Journal$
计算机死信队列 MachineName\Deadletter$
计算机事务性死信队列 MachineName\XactDeadletter$
这里的MachineName能够用 “."代替,表明当前计算机
须要先引用System.Messaging.dll
建立消息队列
1 //消息队列路径 2 string path = ".\\Private$\\myQueue"; 3 MessageQueue queue; 4 //若是存在指定路径的消息队列 5 if(MessageQueue.Exists(path)) 6 { 7 //获取这个消息队列 8 queue = new MessageQueue(path); 9 } 10 else 11 { 12 //不存在,就建立一个新的,并获取这个消息队列对象 13 queue = MessageQueue.Create(path); 14 }
发送字符串消息
1 System.Messaging.Message msg = new System.Messaging.Message(); 2 //内容 3 msg.Body = "Hello World"; 4 //指定格式化程序 5 msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); 6 queue.Send(msg);
发送消息的时候要指定格式化程序,若是不指定,格式化程序将默认为XmlMessageFormatter(使用基于 XSD 架构定义的 XML 格式来接收和发送消息。)
接收字符串消息
1 //接收到的消息对象 2 System.Messaging.Message msg = queue.Receive(); 3 //指定格式化程序 4 msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); 5 //接收到的内容 6 string str = msg.Body.ToString();
发送二进制消息(如图像)
引用 System.Drawing.dll
1 System.Drawing.Image image = System.Drawing.Bitmap.FromFile("a.jpg"); 2 Message message = new Message(image, new BinaryMessageFormatter()); 3 queue.Send(message);
接收二进制消息
1 System.Messaging.Message message = queue.Receive(); 2 System.Drawing.Bitmap image= (System.Drawing.Bitmap)message.Body; 3 image.Save("a.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
获取消息队列的消息的数量
1 int num = queue.GetAllMessages().Length;
清空消息队列
1 queue.Purge();
以图形化的方式查看消息队列中的消息
运行输入 compmgmt.msc,打开计算机管理,选择[服务和应用程序-消息队列]。只要消息队列中的消息没有被接收,就能够在这里查看获得。
示例程序: