Microsoft MSMQ (1)

Source: Internet
Author: User
Tags msmq
Recently, an MSMQ message component has been used in a company's system to ensure stable and secure communication on heterogeneous platforms. there are still many unclear understandings of MSMQ, so I will discuss it with you here. to get a better understanding of MSMQ, I wrote a demo. If you need a friend, please leave an email.
First, I will give you some basic information I have found online:
I. Overview
MSMQ (Microsoft Message Queue, Microsoft Message Queue) 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 puts the information he wants to send into a container (we call it message ), then, it is saved to the message queue in a public space of the system. local or remote message receiving programs then extract the messages sent to it from the queue for processing.

There are two important concepts in the message transmission mechanism. One is a message, and the other is a queue. A message is the information that must be transmitted by both parties. It can be a variety of media, such as text, sound, and image. The final way to understand a message is agreed by both parties. The advantage of this is that 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, so that only the specified user can see the information that is passed to him and the receipt that is returned for successful operation. A message can also contain a timestamp, so that the receiver can process certain time-related applications. A message can also contain an expiration time. It indicates that a message is voided if it has not arrived within the specified time, which is mainly used for time-based applications.

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 modes is that the express delivery mode enables fast delivery of messages, messages are stored in the memory instead of on the physical disk to obtain high processing capability. The recoverable mode is in each step of the transfer process, all messages are written to the physical disk for better fault recovery. Message queues can be placed on the sender and receiver, or separately on another machine. It is precisely because of the flexibility of message queues in the placement mode that the reliability of the message transmission mechanism is formed. When the machine that stores the Message Queue fails and restarts, messages sent in recoverable mode can be restored to the status before the fault occurs, and messages sent by express delivery are lost. On the other hand, using the message transmission mechanism, the sender must worry about whether the receiver is started, whether a fault occurs, and other non-essential factors. As long as the message is successfully sent, the processing can be considered complete, in fact, the other party may not even start the instance, or the next day may have actually completed the transaction.

The application sends a message to MSMQ, while MSMQ uses the message queue to ensure that the message can finally reach its destination. MSMQ provides guaranteed message delivery, effective message routing, security, and priority-based message transmission.
Ii. Main MSMQ functions:
With MSMQ, end users can communicate with each other over the network that sometimes goes offline, so that they are independent of the current state of the communication program and system. Developers can use MSMQ to focus on business processing programming rather than network problems, because MSMQ provides network communication assurance. The system administrator can use MSMQ explorer to effectively manage message queues on large and complex networks. Through MSMQ, MIS decision makers can obtain more reliable communications in review and network-related distributed applications; effectively use network resources; reduce software development and maintenance time; improve productivity from end users, developers and system administrators.
Ii. Basic operations
. Use the create method to create a message queue in the specified path, and use the delete method to delete an existing message queue.
. Use the exists method to determine whether a Message Queue exists.
. Use the getpublicqueues method to obtain a message queue in the message queue network.
. Use the peek or beginpeek method to view messages in the message queue without deleting them.
. Use the receive or upper beginreceive method to retrieve a message from the message queue and delete it from the message queue.
. Use the send method to send a message to the specified message queue.
7.3.3 Message Queue operations
1. Create a Message Queue
. Create a public message queue
Messagequeue. Create ("mymachine \ myqueue ")
. Create a private message queue
Messagequeue. Create ("mymachine \ private $ \ myprivatequeue ")
Description: Private $ indicates that a private message queue is created.

2. Queue reference description

After you create an instance of the messagequeue component, you must specify the queue to communicate. In. Net has three methods to access the specified message queue:
. The path of the message queue is uniquely determined by the machine name and queue name. Therefore, the Message Queue path can be used to specify the message queue used.
. The format name is the unique identifier generated by MSMQ when a message queue is created or after an application is created in the queue.
. A label is a descriptive name specified by the queue manager when a message queue is created.
It may not be unique.

Reference queue using path

Message Queue type path format
Public queue machinename \ queuename
Private queue machinename \ private $ \ queuename
Journal queue machinename \ queuename \ journal $
Machine journal queue machinename \ journal $
Machine dead letter queue machinename \ deadletter $
Machine transactional dead letter queue machinename \ xactdeadletter $

. The Message Queue Server parses the path and format name (format name) when receiving an operation request using the Message Queue path ), therefore, the queue is not as efficient as the format name method.
. When a message queue is not connected, you can only send messages to it using the format name.
In addition to the path attribute, the reference of a path name can also be obtained from the machinename and queuename attributes.
Example of path reference:
Messagequeue1.path = ". \ myqueue"

Use format name to reference a queue
The format name consists of a Public Private ID string, a guid generated by the queue, and other required IDs.

Composition rules of Message Queue Type format names
Public queue public = queueguid
Private queue private = machineguid \ queuenumber
Journal queue public = queueguid; Journal or private = machineguid \ queuenumber; Journal
Foreign queues direct = addressspecification \ queuename

The format name is automatically generated by the queue manager when the queue is created.
. When your component is used as a part of a Web sevice or web call, it is best to reference the queue by format name because it is faster.
. When sending a message to a non-connected queue, the format name should be used, because path resolution will fail when the queue is not connected.
. When the network topology changes or the message queue is rebuilt, the format name changes.
The format name can be obtained by the formatname attribute of the Message Queue object.

For example, the format name is used to reference a message queue.
Messagequeue1.path = "formatname: Public = 3d3dc813-c555-4fd3-8ce0-79d5b45e0d75"

Reference message queue by ID
When a message queue is created, the Message Queue creator specifies the text attribute that describes the queue. The advantage of using the logo is that it shields the specific location of the lower layer. During transplantation and program modification, the application modification is very small. Its disadvantage is also obvious, that is, the uniqueness of the logo cannot be guaranteed. When there is a conflict between the logo, sending a message to the logo will lead to an error. The identifier can be obtained by accessing the label attribute of the Message Queue object.
To sum up, the procedure for referencing a message queue is roughly as follows:
First, generate an instance of the messagequeue object.
Then, set different attributes based on the way the message queue is referenced.
If the path is used, set its path attribute.
If the format name is used, set the formatname attribute.
Set its label attribute if it is the identity method.

3. Delete A Message Queue
Delete a queue. When a queue is deleted, all messages contained in the queue are deleted first, and then deleted. messages in the queue are not sent to the dead-letter queue. The main problem with deleting a queue is whether the user has sufficient permissions to delete the queue.
An example of using the delete method is as follows:
Messagequeue. Delete ("mymachine \ myqueue ")

4. Clear the content in the Message Queue
You can use the purge method provided by the Message Queue object to clear messages that have not been sent to the message queue, or to regularly clear the message sending log queue. It clears all messages in the specified message queue and does not send any messages.
An example is as follows:
Messagequeue1.path = "mymachine \ myqueue"
Messagequeue1.purge ()

5. Create an instance of the Message Queue object
To create a message queue instance, follow these steps:
1. Create a messagequeue class instance
For example:
Dim myque as new messagequeue
2. Set the path attribute of the messagequeue class instance
For example:
Myque. Path = ". \ myqueue"
3. Set attributes of other messagequeue classes.

6. Message Queue configuration attributes

Queue attributes:

Path attribute: it can be used to reference a queue in three ways: path reference, format name reference, and Id reference.
CATEGORY attribute: identifies the type of the currently used queue. Category is the guid value defined by the queue owner. The GUID value can be generated by a guid generation tool or a user-defined numeric value. The GUID value is not unique, so that multiple message queues can be divided into different categories based on the same guid value ).

Attributes related to the data sending type

Formatter attribute: determines the order in which messages are sent and received in a queue, and what content can be sent in a message.

Attributes related to queue Interaction
Denysharereceive attribute: only one component can access messages in the message queue at a time.
Canread and canwrite attributes: determines whether the queue can be read or written.
Maximumqueuesize and maximumjournalsize attributes: set the maximum message capacity of a queue (log queue) in kilobytes. Once the received message reaches this capacity, new messages will no longer be received.
Generally, the maximum value of the message queue is set by the Message Queue administrator. If this value is not controlled, the maximum capacity of the default message queue is unlimited.
Usejournalqueue attribute: sets whether to copy received messages to the log message queue.

7. Send messages
A message defined in MSMQ message queue consists of a body and several attributes. The message body can be composed of text and binary, and can be encrypted as needed. You can assign values to the attributes of a message object in the Properties window. However, the Message Size in MSMQ cannot exceed 4 MB.
Messages can be sent to public, private, log, dead message, and transaction queue.
. Sending of simple messages
The steps for sending a simple message are as follows:
1. Establish a connection with the queue for sending messages
2. Specify the format of the message you want to send
3. provide the data to be sent
4. Use the send method to send messages
The data types sent by sending simple messages can be objects, original data types, data streams, or other simple data types.
Example: sending an integer and a string is used as an example.
First, create a connection:
Dim messagequeue1 as new messagequeue ("mymachine \ myqueue ")
Or
Dim messagequeue1 as new messagequeue
Messagequeue1.path = "mymachine \ myqueue ")

Because it is a standard data type, the message format can be left unspecified and the default

Then, send the value 1.
Messagequeue1.send (1)
Resend the string "Hello World"
Messagequeue1.send ("Hello World ")

. Send complex messages
Compared with simple message sending, sending complex message objects can give you more control over messages. For sending a complex object, we create an instance of the object for the message and set its attributes accordingly.
To send a complex message, follow these steps:
1. Create a messagequeue instance and set its path attribute to specify the operated message queue.
2. Create a message object instance.
3. Set the message body and modify the attributes that do not want to use the default value.
4. Send the message object to the corresponding queue using the send method.
Example:
'Create a messagequeue instance and specify the connected queue
Dim messagequeue1 as new messagequeue (". \ myqueue ")
'Create a message object instance
Dim mymessage as new message ("Hello World ")
'Set message queue attributes
Mymessage. Label = "mylabel"
'Send message
Messagequeue1.send (mymessage)

8. receive messages

Messages are received in two ways: synchronous and asynchronous.
Synchronization method. We use the receive method. When the receive method is called, it selects the first suitable message object from the specified message queue and returns it to the user, and then deletes it from the message queue. If no record exists in the message queue when the receive method is called, the program will be suspended until a message arrives in the message queue. In order not to make the waiting process too long, you can specify the time-out value (in milliseconds) when calling the receive method to exit the waiting process after the corresponding time is reached. When using the receive method, you can also specify the denysharereceive attribute of the message queue to prevent other users from performing operations on the queue. Imagine that when there is one message in the message queue, two users call the peek method at the same time to find that all messages exist, therefore, you can safely use the receive method to obtain the message, and the result will inevitably cause one of the users to be suspended. If the denysharereceive attribute is used before the receive method is called to reject other users' receive methods for this queue, the above phenomenon will be avoided.
Example of synchronous receiving:
Dim mymessageque as messagequeue

Mymessageque = new messagequeue ("mymachine \ myqueue ")
'Specify the message queue to be connected
Dim mymessage as new message
Mymessage = mymessageque. Receive (1000)
'Receive a message synchronously. The timeout time is 1 second.

The peek method is similar to the receive method, but it does not delete the acquired message object from the message queue. The peek method only retrieves the first message in the message queue. To obtain all the messages, you can use the getmessages method or the getmessagesenumrator method. The peek method is also a synchronization method, so when there is no message in the message queue, it will also be suspended until a message is generated. In the same way, you can specify the timeout time (in milliseconds) for peek. Generally, the most common method is set to 0 or infinity. If it is set to 0, the message queue is searched to check whether a message is generated and returns immediately. If it is set to infinity, the message is processed only when a message is generated.
For example:
'Set the timeout value to 0.
Mymessage. timetobereceived = 0

'Set the timeout value to infinity.
Mymessage. timetobereceived = message. Infinite

'Example of using the peek method in synchronous Mode
Dim mymessageque as new messagequeue ("mymachine \ myqueue ")

'Specify the connected Message Queue
'Query the first message in the message queue. If the message queue times out after 1 second, the system returns
Dim mymessage as message
Mymessage = mymessageque. Peek (1000)

Asynchronous receiving means that when receiving a message, you do not have to worry about whether the called message receiving method is successful. The method will return immediately and continue program processing. There are two Processing Methods for messages received in asynchronous mode. One is that after a message is received, an event is generated. We can define an event processing function, in which the received message is processed. Another method is to define a callback function for the message receiving function. After a message is received, it processes the message.
In ASP. NET, In the event processing method, in the event processing function, we use the beginpeek or beginreceive method to retrieve a message from the message queue. To process multiple messages, you must call the beginpeek or beginreceive method repeatedly.
In the callback processing method, the callback function defines a proxy bound to the beginpeek or beginreceive method. In this way, even in message processing, the proxy can still monitor whether new messages have arrived.
Because message processing functions are widely used, the following describes how to use message functions.
In the event model, you must first bind a message processing function to a message, which is the code entry you want to process after the asynchronous call is complete. Then, call the beginreceive method to start the asynchronous receiving mode. When the receiving process is complete, the. NET platform sends a message, indicating that a message has been received from the message queue, and then calls the processing function bound to the message to process the received message.
The procedure is as follows:
① Bind a message processing function to the beginreceivecompleted event of the messagequeue object
② In the beginreceivecompleted processing function, create a message object instance and an instance of a message queue object.
③ Define how to process received information. The code framework is as follows:
Public sub myqueue_beginreceivecompleted (sender as object, argS as system. messaging. receiveasynceventargs)
Dim mymessage as message
Dim mymessageque as messagequeue
Mymessageque = ctype (sender, messagequeue)
Mymessage = mymessageque. endreceive (ARGs. asyncresult)
End sub
④ In the main program, start the asynchronous receiving method using the beginreceive method.
For example:
Mymessageque. beginreceive
The asynchronous receiving mode using the peek method is similar to that using the receive method.

9. Message confirmation

To ensure that a message is correctly sent to the Target message queue, you can also set the message queue to check whether the returned message is correctly sent to the specified queue. There are two types of validation messages: one is the confirmation message sent by the Message Queue after it reaches the specified queue, and the other is that the message is deleted from the message queue by the application of the other party. Each message has two forms: Confirmation and rejection. When a message arrives in the target queue or application correctly, it sends back a successfully sent confirmation message. If the message cannot reach the specified queue or application, it sends back the failed confirmation message. However, if a message fails to be sent, it may not be that the message queue of the other party cannot arrive. It may be that the Message Queue cannot pass the verification of the other party during the time-out period.
The confirmation messages returned from the other party are generally not placed in a general queue, but in a special queue called a management queue. A confirmation message is also different from a general message. It does not contain the message body and can be understood only through the message header.
In ASP. NET, confirm the management queue to which the message is sent, which is determined by the queue specified by its administrationqueue attribute.
You can send different validation messages to different management queues. The operations on queue management are the same as those on different queues. You can use the peek method to view and remove the queue.
So how to set a message and ask it to return confirmation information?
First, set the administrationqueue attribute of a message object to specify the management queue returned by the confirmation message.
Set the confirmation type of the returned message, and use the acknowledge attribute of the message object.
The value of the acknowledge attribute can be:
. Fullreachqueue returns a confirmation message no matter whether the sent message arrives or cannot reach the destination queue.
. Fullreceive returns a confirmation message no matter whether the message is sent to the recipient's application.
. Notacknowledgereachqueue returns a confirmation message only when the sent message fails to reach the destination queue.
. Notacknowledgereceive returns a confirmation message only when the sent message fails to reach the recipient's application.
. None No confirmation message is returned
Finally, send the message and check the management queue to check whether the message is generated.

10. Message Log

The log queue can store backups of messages you have performed. The advantage is that, once the previous operation fails, you can re-create the original message object from the log queue and then perform the operation. For example, send a message object to a remote location, and then the recipient returns a failed confirmation. We can extract an id value related to the start message from the failure confirmation message, and find the sent message from the log queue according to the proposed id value, re-create a message object and send it again. In. net, we use the receivebycorrelationid or peekbycorrelationid method to obtain the message object based on the correlation id value.
On a machine, a global message queue stores any messages sent from the machine, regardless of whether the message is successfully sent. Each Message Queue can also have its own message log queue. There are two ways to use the log queue. One is to set the usejournalqueue attribute for the message queue object, which indicates that all messages received by the queue are logged, the system does not record the sent messages. Another method is to set the usejournalqueue attribute for the message object. All sent messages are recorded in the system log queue. The maximum capacity of the message queue is quota. Once the storage capacity of the log queue reaches this value, messages that should be stored will no longer be stored, no error message is sent. As a manager, you should regularly clean up the log queue to prevent the above phenomenon. Message Queues are only passive receivers. They cannot return confirmation messages, send deleted messages to dead message queues, or perform timeout processing.
Example:
Sets the usejournalqueue attribute of the Message Queue object to record received messages to the log queue.
Mymessagequeue. usejournalqueue = true

Set the usejournalqueue attribute of the message object to record received messages to the system log queue.
Mymessage. usejournalqueue = true

Now you can create your own MQ on the computer.

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: info-contact@alibabacloud.com 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.