Introduction to Microsoft Message Queue (MSMQ)

Source: Internet
Author: User
Tags net message queue msmq

I was doing a program design with clicks a year ago. Now I have no choice but to post it. I will share my thoughts on Program Design: considering that there are too many interactions between clicks and databases, in order to reduce the pressure on the Web server, I decided to try MSMQ (Microsoft Message Queue) and make a preliminary attempt on MSMQ. If there are any problems, please follow up.
The specific design idea is as follows: a message will be sent when the front-end page is opened. Because the message queue is asynchronous, the front-end performance is not particularly affected, there is a special windows console program in the background to automatically and asynchronously receive messages sent from the foreground, and then perform business processing (mainly to update the database ), this greatly reduces the pressure on Web servers.
A Brief Introduction to the concept of Message Queue:
● "Message": refers to the Data Unit transmitted between two computers. Messages can be very simple, for example, containing only text strings, or more complex, and may contain embedded objects.
● "Message queue": a container that stores messages during message transmission. The message queue manager acts as a man-in-the-middle when a message is relayed from its source to its target. The main purpose of a queue is to provide a route and ensure message transmission. If the receiver is unavailable when a message is sent, the Message Queue retains the message until it can be passed successfully.
● "Message queue" is Microsoft's message processing technology. It provides message processing and Message Queue functions for any application in any computer combination installed with Microsoft Windows, whether these computers are on the same network or online at the same time.
Queue type:
● User queue
-Public queue: It is replicated across the "message queue" network and may be accessed by all sites connected to the network.
-"Dedicated queue" is not released throughout 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 the message that confirms the receipt of messages sent in the given "message queue" network.
-The "response queue" contains the response message returned to the application when the target application receives the message.
● System queue
-"Diary queue" can be used to store copies of sent messages and the pairs of messages removed from the queue.
-"Dead-letter queue" stores copies of messages that cannot be passed or have expired.
-The "Report queue" contains the messages that indicate the route for the message to reach the target, and can also contain test messages. Each computer can have only one report queue.
-"Dedicated system queue" is a dedicated queue for managing and notifying messages required by a series of storage systems to perform message processing operations.

Advantages of using message queue:
● Stability-the impact of component failure on messages is much smaller than that of direct calls between components, because messages are stored in the queue and remain there until they are properly processed.
● Message priority-more urgent or important messages can be received before less important messages, so that sufficient response time can be guaranteed for key applications.
● Offline capabilities-when messages are sent, they can be sent to the temporary queue and stay there until they are successfully transmitted.
● Security-messagequeue component-based message queue technology uses Windows security to protect access control, provide audit, and encrypt and verify messages sent and received by the component.
Programming advantages:
● With Microsoft Windows message queue, application developers can send and receive messages to facilitate fast and reliable communication with applications.
● Like XML Web Services and. Net remoting, MSMQ is a distributed development technology. However, when using XML Web Services or. net remoting component, the client needs to exchange information with the server in real time, and the server needs to stay online. MSMQ can work when the server is offline. The message is temporarily stored in the client message queue, and then sent to the server for processing when the server is online.
● The advantage of MSMQ is that, due to asynchronous communication, the sender and receiver can execute the remaining code without waiting for the other party to return a successful message, this greatly improves the processing capability of things.
Development practices:
First, ensure that the MSMQ Service is installed on the server. Specifically, choose Control Panel> Add/delete component> Add/delete winwows component (A)-Message queue. For details, see.
The image of this topic is as follows:

We only need. you can develop your own program in the messaging namespace. easy to use. for details, refer to the messagequeue and message classes. It is very convenient and simple to use.
In addition, the following issues are raised about Message Queue serialization:
. Net message queue provides the following format programs:
● Xmlmessageformatter, binarymessageformatter, and activexmessageformatter type features.
Xmlmessageformatter: This is the default formatter. The previous example uses it. We can think of it from this name. It will serialize the custom type into an XML Representation, this formatting program is very slow and will create a relatively large number of messages. However, these messages can be shared and understood by applications running on different platforms.
● Binarymessageformatter The formatter application will serialize the custom type into a proprietary binary format. It is much faster than the above one, and the generated messages are very compact. However, only the receiver running in. Net can easily parse the message content.
● Activexmessageformatter: similar to binarymessageformatter, activexmessageformatter serializes custom types into dedicated binary formats. This format is used by the COM component of MSMQ. These traditional COM components provide MSMQ-based functions for the com language (such as Visual Basic 6. Therefore, you can use this formatting program in the MSMQ application compiled in Visual Basic 6 to send or receive messages. Note that, unlike xmlmessageformatter, binarymessageformatter uses binary format to serialize objects to the message body. In fact, he uses the same serialization mechanism as the. NET remoting Runtime Library, which means to use the serializable feature to modify the type. At the same time, he is not as flexible as the default format, although the speed is fast and more compact. However, both the sender and receiver must have a copy of the Assembly.
Xmlmessageformatter is generally used.
That is, when a message is received and processed, the serialization format needs to be formulated. For example:
Messagequeue MQ = (messagequeue) sender;
System. messaging. Message message = MQ. endreceive (E. asyncresult );
Message. formatter = new xmlmessageformatter (New Type [] {typeof (bitauto. UCAR. Website. BLL. ucarclickmana. ucarclickmessage); // This is the message object we want
Ucarclickmessage model = message. Body as ucarclickmessage;
Queue path reference:
● Path-the path that uniquely identifies the name of the computer and the queue of interest.
-Public queue machinename/queuename
-Dedicated queue machinename/private $/queuename can be specified with./private $/queuename on the local machine.
● The message queue is generated by MSMQ when the queue is created using the format name, the unique identifier of the queue, which is later generated by the application.
-Public queue formatname: Public = queueguid
-Dedicated queue formatname: Direct = OS: {machinename}/private $/{queuename}
Formatname: Direct = TCP: {IP}/private $/{queuename}
● Use tags -- a descriptive queue name that may not be unique. The queue administrator assigns this name when creating a queue.
-Messagequeue1.path = "label: myqueue ";
Case program:
Automatic background receiving program:

Using system;
Using system. Collections. Generic;
Using system. text;
Using system. messaging;
Using UCAR. Common;
Using bitauto. UCAR. nettiers. Data;
Using bitauto. UCAR. nettiers. entity;
Using bitauto. UCAR. Website. BLL. ucarclickmana;
* Module: Vehicle source clicks statistics
* File function: automatically modifies the vehicle source clicks.
* Author: Wang Jianfeng
* Creation Time:
Namespace msmqreceiveauto
/** // <Summary>
/// The binary object responsible for receiving the sequence sent by the web layer Asynchronously
/// The object currently contains the bitauto. UCAR. nettiers. entity. ucarclicktotalinfo data type.
/// </Summary>
Class Program
Static void main (string [] ARGs)
String ucarclickpath = confighelper. getreceivetting ("msmqpath ");
System. messaging. messagequeue queue = new messagequeue (ucarclickpath );
Queue. receivecompleted + = new receivecompletedeventhandler (queue_receivecompleted );
Queue. beginreceive ();
Catch (exception ex)
Console. writeline (ex. tostring ());
Loghelper. errorlog (ex, appdomain. currentdomain. basedirectory + "/log.txt ");
System. Console. Readline ();

Receive events in the queue # receive events in the region queue
Private Static void queue_receivecompleted (Object sender, receivecompletedeventargs E)
Number of threads # Number of region threads
// Control the server load within a certain number of threads
// At the same time, ensure that threads cannot accumulate,
# Endregion

Int mdowithmsmqtimespan = 2;
System. Threading. thread. Sleep (mdowithmsmqtimespan );

Messagequeue MQ = (messagequeue) sender;
System. messaging. Message message = MQ. endreceive (E. asyncresult );

Message. formatter = new xmlmessageformatter (New Type []... {typeof (bitauto. UCAR. Website. BLL. ucarclickmana. ucarclickmessage )});
Ucarclickmessage model = message. Body as ucarclickmessage;

If (model! = NULL)
Ucarclickcountmsmq. dowithmessage (model );
// Prompt message
Console. writeline ("============= asynchronous receiving start =========== ");
Console. writeline ("ucarid to be processed:" + model. ucarid. tostring ());
Console. writeline ("message creation time:" + model. createtime. tostring ());
Console. writeline ("message receipt time:" + system. datetime. Now. tostring ());
Console. writeline ("============= asynchronous receipt succeeded =========== ");
Console. Write ("");
MQ. beginreceive ();
# Endregion


Highly concurrent and scalable Web design. One important idea is decoupling between different systems. The asynchronous and reliable MSMQ is very valuable.

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.