MSMQ是微软消息队列的英文缩写。那么什么是消息队列?这些介绍网上一大片这里就不多说了。本文对于大虾级的人物来说这只是小玩意而已,对于初学者来说这文章还是有一定的帮助,希望路过的大虾们别笑话我班门弄斧。
一、MSMQ介绍和安装消息队列
      关于MSMQ详细的介绍请大家向http://www.baidu.com/或http://www.g.cn/等专家咨询。
      使用消息队列的优点:稳定、消息优先级、脱机能力以及安全性。
      消息队列分为用户创建的队列(专用队列)和系统队列,用户队列分为,。我是Windows XP,看下图所示(myQueue为自己创建的消息队列,msmqtriggersnotifiations为通用队列):
               
     对消息队列有了简单的了解后,使用MSMQ进行软件开发需要安装MSMQ,安装完后就该进入实际的开发阶段。具体的安装过程就是在控制面板里“添加/删除程序”下“添加/删除Windows组件”,完成添加就OK。安装完成后就可以通过交互界添加新的消息队列,详细如下图:
          
      出了上面这种交互界面来创建MSMQ外,也可以通过编程来完成,.NET框架里的MessageQueue类下有一静态方法Create,用来完成消息队列的创建,其定义如下:
 //
// // 摘要:
// 摘要: //    在指定的路径中创建非事务性“消息队列”队列。
//    在指定的路径中创建非事务性“消息队列”队列。 //
// // 参数:
// 参数: //   path:
//   path: //     要创建的队列的路径。
//     要创建的队列的路径。 //
// // 返回结果:
// 返回结果: //     表示新队列的 System.Messaging.MessageQueue。
//     表示新队列的 System.Messaging.MessageQueue。 public static MessageQueue Create(string path);
public static MessageQueue Create(string path); //
// // 摘要:
// 摘要: //     在指定的路径中创建事务性或非事务性“消息队列”队列。
//     在指定的路径中创建事务性或非事务性“消息队列”队列。 //
// // 参数:
// 参数: //   transactional:
//   transactional: //     如果创建事务性队列,为 true;如果创建非事务性队列,则为 false。
//     如果创建事务性队列,为 true;如果创建非事务性队列,则为 false。 //
// //   path:
//   path: //     要创建的队列的路径。
//     要创建的队列的路径。 //
// // 返回结果:
// 返回结果: //     表示新队列的 System.Messaging.MessageQueue。
//     表示新队列的 System.Messaging.MessageQueue。 public static MessageQueue Create(string path, bool transactional);
public static MessageQueue Create(string path, bool transactional);
     实现消息队列的创建简单代码(C#),创建一个名为"myQueue"的非事务性"消息队列",如下:
 MessageQueue.Create(@".\private$\myQueue");
MessageQueue.Create(@".\private$\myQueue");
二、创建、删除和管理队列
      在.NET环境下编写Message Queue程序的前提就是需要先安装MSMQ,本文之前已经作了详细的介绍。要开发MSMQ程序就必须学习一个很重要的类(MessageQueue),该类位于名称空间System.Messageing下。其中有几个常用的方法必须掌握:
  --Create方法:创建使用指定路径的新消息队列。
  --Delete方法:删除现有的消息队列。
  --Existe方法:查看指定消息队列是否存在。
  --GetAllMessages()方法:得到队列中的所有消息。
  --GetPublicQueues方法:在“消息队列”网络中定位消息队列。
  --Peek/BeginPeek方法:查看某个特定队列中的消息队列,但不从该队列中移出消息。
  --Receive/BeginReceive方法:检索指定消息队列中最前面的消息并将其从该队列中移除。
  --Send方法:发送消息到指定的消息队列。
  --Purge方法:清空指定队列的消息。
    上述列举的方法在此就不作详细介绍,大家可以通过下面的示例程序中来体会他们各自的功能。
三、发送和序列化消息
     MSMQ消息队列中定义的消息由一个主体(body)和若干属性构成。消息的主体可以由文本、二进制构成,根据需要还可以被加密。在MSMQ 中消息的大小不能够超过4MB。发送消息是通过Send方法来完成的,需要一个Message参数。
1、发送消息:
     步骤:连接队列-->指定消息格式-->提供要发送的数据(主体)-->调用Send()方法将消息发送出去。详细见后面的示例程序。
     
2、序列化消息:
     消息序列化可以通过.NET Framework附带的三个预定义格式化程序来完成:
    --  XMLMessageFormatter对象----MessageQueue组件的默认格式化程序设置。
    --  BinaryMessageFormatter对象;
    --  ActiveXMessageFormatter对象; 
    由于后两者格式化后的消息通常不能为人阅读,所以我们经常用到的是XMLMessageFormatter对象。该对象构造方法有三种重载:
 public XmlMessageFormatter();
public XmlMessageFormatter(); public XmlMessageFormatter(string[] targetTypeNames);
public XmlMessageFormatter(string[] targetTypeNames); public XmlMessageFormatter(Type[] targetTypes);
public XmlMessageFormatter(Type[] targetTypes);如我们后面的示例程序中用到的序列化语句:
 //序列化为字符串
//序列化为字符串 XmlMessageFormatter formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
XmlMessageFormatter formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
四、读取和接收消息
1、读取消息:
    也就是从指定队列中获取消息,详细请查看本文前面的关于消息操作的方法介绍。
2、接收消息有两种方式:
    --> 通过Receive方法--具体功能请返回本文前面有详细介绍。
    --> 通过Peek方法--具体功能请返回本文前面有详细介绍。
五、消息使用实例
     通过上面一系列的介绍,了解了MessageQueue类和常用的方法后,下面我们通过一个简单的示例程序来分析消息队列的创建、发送消息以及接收消息等相关知识点:
1、通过Create方法创建使用指定路径的新消息队列
 /// <summary>
/// <summary> /// 通过Create方法创建使用指定路径的新消息队列
/// 通过Create方法创建使用指定路径的新消息队列 /// </summary>
/// </summary> /// <param name="queuePath"></param>
/// <param name="queuePath"></param> public static void Createqueue(string queuePath)
public static void Createqueue(string queuePath) {
{ try
    try {
    { if (!MessageQueue.Exists(queuePath))
        if (!MessageQueue.Exists(queuePath)) {
        { MessageQueue.Create(@".\private$\myQueue");
            MessageQueue.Create(@".\private$\myQueue"); }
        } else
        else {
        { Console.WriteLine(queuePath + "已经存在!");
            Console.WriteLine(queuePath + "已经存在!"); }
        } }
    } catch (MessageQueueException e)
    catch (MessageQueueException e) {
    { Console.WriteLine(e.Message);
        Console.WriteLine(e.Message); }
    } }
}
2、连接消息队列并发送消息到队列
 /// <summary>
/// <summary> /// 连接消息队列并发送消息到队列
/// 连接消息队列并发送消息到队列 /// </summary>
/// </summary> public static void SendMessage()
public static void SendMessage() {
{ try
    try {
    { //连接到本地的队列
        //连接到本地的队列 MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
        MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue"); 
         Message myMessage = new Message();
        Message myMessage = new Message(); myMessage.Body = "消息内容";
        myMessage.Body = "消息内容"; myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
        myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); //发送消息到队列中
        //发送消息到队列中 myQueue.Send(myMessage);
        myQueue.Send(myMessage); }
    } catch (ArgumentException e)
    catch (ArgumentException e) {
    { Console.WriteLine(e.Message);
        Console.WriteLine(e.Message); }
    } }
}
3、连接消息队列并从消息队列中接收消息
 /// <summary>
/// <summary> /// 连接消息队列并从队列中接收消息
/// 连接消息队列并从队列中接收消息 /// </summary>
/// </summary> public static void ReceiveMessage()
public static void ReceiveMessage() {
{ //连接到本地队列
    //连接到本地队列 MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
    MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue"); myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
    myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); try
    try {
    { //从队列中接收消息
        //从队列中接收消息 Message myMessage = myQueue.Receive();
        Message myMessage = myQueue.Receive(); string context = (string)myMessage.Body; //获取消息的内容
        string context = (string)myMessage.Body; //获取消息的内容 Console.WriteLine("消息内容为:" + context);
        Console.WriteLine("消息内容为:" + context); }
    } catch (MessageQueueException e)
    catch (MessageQueueException e) {
    { Console.WriteLine(e.Message);
        Console.WriteLine(e.Message); }
    } catch (InvalidCastException e)
    catch (InvalidCastException e) {
    { Console.WriteLine(e.Message);
        Console.WriteLine(e.Message); }
    } }
}
4、连接队列并清空队列的全部消息
 /// <summary>
/// <summary> /// 清空指定队列的消息
/// 清空指定队列的消息 /// </summary>
/// </summary> public static void ClearMessage()
public static void ClearMessage() {
{ MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
    MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue"); myQueue.Purge();
    myQueue.Purge(); }
}
5、连接队列并获取队列的全部消息
 /// <summary>
/// <summary> /// 连接队列并获取队列的全部消息
/// 连接队列并获取队列的全部消息 /// </summary>
/// </summary> public static void GetAllMessage()
public static void GetAllMessage() {
{ //连接到本地队列
    //连接到本地队列 MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
    MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue"); Message[] message = myQueue.GetAllMessages();
    Message[] message = myQueue.GetAllMessages(); XmlMessageFormatter formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
    XmlMessageFormatter formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); for (int i = 0; i < message.Length; i++)
    for (int i = 0; i < message.Length; i++) {
    { message[i].Formatter = formatter;
        message[i].Formatter = formatter; Console.WriteLine(message[i].Body.ToString());
        Console.WriteLine(message[i].Body.ToString()); }
    } }
}
     上面依次的列举出来5个方法,这里我就不做测试了。上述方法全部通过测试的,我在后面提供个连接,没弄清楚的朋友可下载源程序自己去运行调试下。
 本实例完整代码
本实例完整代码
六、复杂消息发送实例
     通过上面一系列的介绍,对于简单消息的发送和接收及消息的管理应该都不会有什么问题了,下面我在介绍一下关于复杂的消息处理,现在有这样一个需求,要求通过消息队列将一本图书信息发送到队列里,然后从消息队列里读取出来。图书的基本信息包括图书编号、图书名称、图书作者以及图书定价,这样的一个复杂的对象类型怎么来传输呢?详细如下:
 Book对象
Book对象
 namespace MSMQ.App
namespace MSMQ.App {
{ public class MsgQueue
    public class MsgQueue {
    { /// <summary>
        /// <summary> /// 通过Create方法创建使用指定路径的新消息队列
        /// 通过Create方法创建使用指定路径的新消息队列 /// </summary>
        /// </summary> /// <param name="queuePath"></param>
        /// <param name="queuePath"></param> public static void Createqueue(string queuePath)
        public static void Createqueue(string queuePath) {
        { try
            try {
            { if (!MessageQueue.Exists(queuePath))
                if (!MessageQueue.Exists(queuePath)) {
                { MessageQueue.Create(@".\private$\myQueue");
                    MessageQueue.Create(@".\private$\myQueue"); MessageBox.Show("创建队列成功!");
                    MessageBox.Show("创建队列成功!"); }
                } else
                else {
                { MessageBox.Show(queuePath + "已经存在!");
                    MessageBox.Show(queuePath + "已经存在!"); }
                } }
            } catch (MessageQueueException e)
            catch (MessageQueueException e) {
            { MessageBox.Show(e.Message);
                MessageBox.Show(e.Message); }
            } }
        }
 /// <summary>
        /// <summary> /// 连接消息队列并发送消息到队列
        /// 连接消息队列并发送消息到队列 /// </summary>
        /// </summary> public static bool SendMessage(Book book)
        public static bool SendMessage(Book book) {
        { bool flag = false;
            bool flag = false; try
            try {
            { //连接到本地的队列
                //连接到本地的队列 MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
                MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
 System.Messaging.Message myMessage = new System.Messaging.Message();
                System.Messaging.Message myMessage = new System.Messaging.Message(); myMessage.Body = book;
                myMessage.Body = book; myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) });
                myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) }); //发送消息到队列中
                //发送消息到队列中 myQueue.Send(myMessage);
                myQueue.Send(myMessage); flag = true;
                flag = true; }
            } catch (ArgumentException e)
            catch (ArgumentException e) {
            { MessageBox.Show(e.Message);
                MessageBox.Show(e.Message); }
            } return flag;
            return flag; }
        }
 /// <summary>
        /// <summary> /// 连接消息队列并从队列中接收消息
        /// 连接消息队列并从队列中接收消息 /// </summary>
        /// </summary> public static string ReceiveMessage()
        public static string ReceiveMessage() {
        { //连接到本地队列
            //连接到本地队列 MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
            MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue"); myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) });
            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) }); try
            try {
            { //从队列中接收消息
                //从队列中接收消息 System.Messaging.Message myMessage = myQueue.Receive();
                System.Messaging.Message myMessage = myQueue.Receive(); Book book = (Book)myMessage.Body; //获取消息的内容
                Book book = (Book)myMessage.Body; //获取消息的内容 return string.Format("编号:{0},书名:{1},作者:{2},定价:{3}",
                return string.Format("编号:{0},书名:{1},作者:{2},定价:{3}", book.BookId,
                    book.BookId, book.BookName,
                    book.BookName, book.BookAuthor,
                    book.BookAuthor, book.BookPrice);
                    book.BookPrice); }
            } catch (MessageQueueException e)
            catch (MessageQueueException e) {
            { MessageBox.Show(e.Message);
                MessageBox.Show(e.Message); }
            } catch (InvalidCastException e)
            catch (InvalidCastException e) {
            { MessageBox.Show(e.Message);
                MessageBox.Show(e.Message); }
            } return null;
            return null; }
        } }
    } }
}
     其实发送复杂的消息也就是在消息序列化上有些差别,别的地方与发送普通文本消息没什么大的变化,上面类里提供了创建队列,发送消息到队列,从队列获取消息三个方法,测试结果如下:
                                 
     上示例中,完成了一个复杂类型的消息发送到队列及从队列中读取的演义,详细请下载代码查看:
   点击这里下载本文示例代码
     本文就简单介绍于此,更深入的学习MSMQ请查阅相关资料(如PetShop4里的定单处理策略)。
相关文章连接:
原文:http://www.cnblogs.com/tonykan/p/4416076.html