列表J
message.Formatter = new System.Messaging.XmlMessageFormatter( newType[1] { typeof(MessageContent) } ); |
既然我们已经给消息指定了一个格式化器,我们可以从消息中提取MessageContent对象。但在这之前,我们需要把message.Body属性的返回值分配给一个MessageContent对象。
列表K
MessageContent content = (MessageContent)message.Body; |
在这个例子中,“content”变量是我们向队列发送的原始MessageContent对象的序列化版本,我们可以访问原始对象的所有属性和值。
设定消息优先级别
在正常情况下,队列中的消息以先进先出的形式被访问。这表示如何你先发送消息A,再发送消息B,那么队列将首先返回消息A,然后才是消息B。在多数情况下,这样处理没有问题。但是,有时,由于一条消息比其它消息更加重要,你希望将它提到队列前面。要实现这种功能,你就需要设定消息优先级别。
一条消息的优先级别由它的Message.Priority属性值决定。下面是这个属性的所有有效值(全部来自MessagePriority的列举类型):
·最高(Highest)
·非常高(VeryHigh)
·高(High)
·高于正常级别(AboveNormal)
·正常(Normal)
·低(Low)
·非常低(VeryLow)
·最低(Lowest)
消息在队列中的位置由它的优先级别决定——例如,假如队列中有四条消息,两条消息的优先级别为“正常”(Normal),另两条为“高”(High)。则队列中消息排列如下:
·High Priority A——这是发送给队列的第一条“高”优先级消息。
·High Priority B——这是发送给队列的第二条“高”优先级消息。
·Normal Priority A——这是发送队列的第一条“正常”优先级消息。
·Normal Priority B——这是发送队列的第二条“正常”优先级消息。
根据这个顺序,如果我们给队列发送另一条“最高”优先级的消息,它将位于队列的顶部。
如果需要使用消息优先级功能,你必须修改发送消息的代码。因为Message对象的构造器没有指定消息优先级别的功能,你必须实例化一个 Message对象,并在将它发送给队列之前给它设定相应的属性。列表L中的代码说明如何设定优先级别,并给队列发送一条“最高”优先级别的消息。
列表L
//Instantiate the queue MessageQueue queue = newMessageQueue(queueName); //Create a XmlSerializer for the object type we're sending. XmlSerializer serializer = new XmlSerializer(typeof(MessageContent)); //Instantiate a new message. System.Messaging.Message queueMessage = new System.Messaging.Message(); //Set the priority to Highest. queueMessage.Priority = MessagePriority.Highest; //Create our MessageContent object. MessageContent messageContent = newMessageContent("Hello world - IMPORTANT!"); //Serialize the MessageContent object into the queueMessage. serializer.Serialize(queueMessage.BodyStream, messageContent); //Send the message. queue.Send(queueMessage, "HIGH PRIORITY"); |
这段代码和上面代码的最明显区别在于它使用了XmlFormatter。它实际是可选的,列表L中的代码也可用列表M中的代码代替。
列表M
//Instantiate a new message. System.Messaging.Message queueMessage = new System.Messaging.Message(); //Set the priority to Highest. queueMessage.Priority = MessagePriority.Highest; //Create our MessageContent object. MessageContent messageContent = newMessageContent("Hello world - IMPORTANT!"); //Set the body as the messageContent object. queueMessage.Body = messageContent; //Send the message. queue.Send(queueMessage, "HIGH PRIORITY"); |
这段代码执行和列表L中的代码相同的任务,但代码更少。
应用
输入消费者请求是MSMQ功能的一个简单实例。消费者提出一个请求,由一个面向消费者的应用程序将它送交给消息队列。向队列发送请求后,它会向消费者送出一个确认(acknowledgement)。
然后,一个独立的进程从队列中提取消息,并运行任何所需的业务逻辑(business logic)。完成业务逻辑后,处理系统将向另一个队列提交一个响应。接下来,面向消费者的应用程序从队列中提取这个响应,并给消费者返回一个响应。
这种类型的配置能够加快面向消费者的应用程序的速度,使其迅速做出反应,同时在一个内部系统中完成大量处理工作。这样还可以将请求处理分散到多台内部机器上,提供可扩展性。