Required knowledge for distributed development of WCF (1): MSMQ Message Queue

Source: Internet
Author: User
Tags msmq

This chapter describes the basic concepts and development process of MSMQ.
Microsoft Message Queue (MSMQ) is an asynchronous transmission mode for communication between multiple different applications. Applications that communicate with each other can be distributed on the same machine, it can also be distributed anywhere in the connected network space.
Its implementation principle is: the message sender should put the information he wants to send into a container (we call it message ), save it to a message queue in the public space of the system. The local or remote message receiving program then extracts the messages sent to it from the queue for processing.
There are two important concepts. One is the message, and the other is the queue.

A message can be a variety of media, such as text, sound, and images. The final understanding of the message is agreed by both parties in advance. The advantage is that, first, data is encrypted simply, second, you can use your own defined format to save the amount of communication transferred. A message can contain the sender and receiver IDs. Only the specified user can view the receipt.
Timestamp, which allows the receiver to process certain time-related applications. End time. If the message arrives within the specified time range, it is voided.

The queue types mainly include the following:
The "Public queue" is replicated throughout the message queue network and may be accessed by all sites connected to the network.
"Dedicated queue" is not released across the network. Instead, they are only available on the local computer where they reside. A dedicated queue can only be accessed by applications that know the full path name or tag of the queue.
"Management queue" contains messages that confirm the receipt of messages sent in a given "message queue" network. Specifies the management queue to be used by the messagequeue component (if any)
The "response queue" contains the response message returned to the sending application when the target application receives the message. Specify the response queue (if any) to be used by the messagequeue component ).

A message queue is a public storage space for sending and receiving messages. It can exist in memory or physical files. Messages can be sent in two ways: Express and recoverable. The difference between express and recoverable is that the messages are stored in the memory, the recoverable mode is stored on a physical disk.

Advantages and disadvantages of Message Queue
Advantages: stable, message priority, offline capabilities and security, reliable fault-like mechanism that ensures message transmission and executes many business processes.
Disadvantage: MSMQ is not suitable for the real-time interaction between the client and the server. When a large number of requests are sent, the response latency is high.

First, install the Message Queue Server and enable the Message Queue Service. The following code is used:

First, create a console Project (of course you can also create a web or winform application ). add project reference system. messaging, because all the class libraries related to message queue are encapsulated in system. messaging. in the DLL assembly. next we will write our own code.


using System;using System.Collections.Generic;using System.Linq;using System.Messaging;using System.Text;using System.Threading.Tasks;using Model;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            string msmqName = @".\YXLMSMQ";            string privateMsmqName = @".\Private$\YXLMSMQ";            //你在创建公有队列,而你的机器不属于任何域。一般工作组安装的计算机只能创建私有队列。            //if (!MessageQueue.Exists(msmqName))//判断此路径下是否已经有该队列            //{            //    using (MessageQueue mq = MessageQueue.Create(msmqName))            //    {            //        mq.Label = "YXLPublicQueue"; //设置队列标签            //        Console.WriteLine(mq.Path); //队列路径            //        Console.WriteLine(mq.QueueName);            //        mq.Send("Send To MSMQ Object", "YXLMSMQLabel");//发送消息            //    }            //}            //创建私有消息队列            if (!MessageQueue.Exists(privateMsmqName))//判断此路径下是否已经有该队列            {                using (MessageQueue mq = MessageQueue.Create(privateMsmqName))                {                    mq.Label = "YXLPrivateQueue"; //设置队列标签                    Console.WriteLine(mq.Path); //队列路径                    Console.WriteLine(mq.QueueName);                    mq.Send("Send To Private MSMQ Object", "YXLMSMQLabel1");//发送消息                }            }            //获取公共消息队列并且发送消息            //foreach (MessageQueue mq in MessageQueue.GetPublicQueues())            //{            //    mq.Send("Sending MSMQ public message" + DateTime.Now.ToLongDateString(), "YXLMSMQLabel");//发送公共消息            //    Console.WriteLine(mq.Path);            //}            //找到私有的消息队列并且发送消息            if (MessageQueue.Exists(privateMsmqName))//判断此路径下是否已经有该队列            {                using (MessageQueue mq = new MessageQueue(privateMsmqName))                {                    //mq.Send("Send MSMQ Private message" + DateTime.Now.ToLongDateString(), "YXLMSMQLabel2");            //发送复杂类型                    mq.Send(new User() {Id = 1, Name = "张三"}, "YXLMSMQLabelUser");                    //发送消息到私有队列里                    Console.WriteLine(mq.Path);                }            }        }    }   }


The more important class is messagequeue. This line of code creates the Message Queue messagequeue MQ = messagequeue. create (privatemsmqname). The parameter is the location where the message queue is stored. this completes the main program for creating and sending messages. next we will create a client to access the message queue and obtain the message. We will also create a console application to add references and code:


using System;using System.Collections.Generic;using System.Linq;using System.Messaging;using System.Text;using System.Threading.Tasks;using Model;namespace ConsoleApplicationMSMQClient{    class Program    {        static void Main(string[] args)        {                       string privateMsmqName = @".\Private$\YXLMSMQ";                      //找到私有的消息队列并且发送消息            if (MessageQueue.Exists(privateMsmqName))//判断此路径下是否已经有该队列            {                using (MessageQueue mq = new MessageQueue(privateMsmqName))                {                    //mq.Formatter = new XmlMessageFormatter(new string[]{"System.String"});//设置消息队列格式化器                       //Console.WriteLine(message.Body);                     mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(User) });                    Message message =  mq.Receive();                    User user = message.Body as User;                    Console.WriteLine(user.Id+"-------"+user.Name);                }            }        }    }}


A Message Queue object needs to be instantiated for message receiving. Using (messagequeue MQ = new messagequeue (privatemsmqname) creates a Message Queue object. second, MQ. formatter = new xmlmessageformatter (New String [] {"system. string "}) This line of code is responsible for setting the Formatter for the message queue, because there is a formatting problem in the message transmission process. when receiving a message, you must specify the formatter attribute of the message queue to receive the message. xmlmessageformatter serializes messages in XML format. binarymessageformatter format the message as binary data for transmission. activexmessageformatter also formats messages in binary format. The difference is that you can use com to read messages in the queue.

Of course, the Message Queue can also send complex objects, provided that the object must be serializable. The specific format depends on the formatter settings of the queue. in addition, MQ also supports transaction queues to ensure that messages are sent only once and in the order of sending.

Required knowledge for distributed development of WCF (1): MSMQ Message Queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.