Developers often encounter the need to perform operations asynchronously (that is, the process starts before the operation is completed ). MQ provides a central location or pool where you can place or extract data to meet this requirement. One application can store messages in the queue, and then continue its own business. The other application can extract the data at runtime.
The message component of the queue name is often confusing to developers because they are used to processing mail messages, but the message part of the message queue is composed of data. It provides guaranteed message transmission for applications.
This article describes how to use Microsoft Message Queuing (MSMQ) and. NET Framework message queues.
Why Message Queue
You may think that you can use a simple database table (one application writes data to it, and the other application reads data from it) to apply message queues. Message Queue platforms are more stable because they generally have their own security mechanisms, transaction support, and other functions. The routing function for message transmission is a key application. MSMQ provides various Message Queue platforms.
MSMQIntroduction
MSMQ is a component of Windows 2000, Windows XP, and Windows Server 2003 and will be included in Windows Vista and later Windows servers. Even if the target receiving application is not running, or the computer that runs the sending or receiving application is not connected to the Internet, collaborative applications can still use MSMQ to send and receive messages between each other. Before reaching the target queue, MSMQ stores and forwards messages. The receiving application can recover data from the queue.
MSMQ and other message queues feature separation of sending and receiving applications so that they do not have to run at the same time. This means that an application can store data in the queue, regardless of whether the project in the queue is transmitted to the receiving application.
MSMQ is an optional component of windows. You only need to add or delete Windows components through the Windows Control Panel Wizard to install MSMQ. MSMQ has two configuration modes: domain mode or workgroup mode (only private queue is used ). After MSMQ is installed, it can be run in the. NET application immediately.
MSMQInteraction
The development of message-based applications starts from the queue. MSMQ contains four queue types:
- Outbound queue: Use a message to temporarily store the message before it is sent to the destination.
- Public queue: Published in the Active Directory. Applications on various servers in the network can locate and apply public queues through active directories.
- Private queue: These are queues on the local server and are invalid for other servers (so these queues are not published in the Active Directory .)
- System queue: Includes the diary Queue (generated by the system), dead queue, and transaction-type dead message queue. Dead messages cannot be sent.
The system. messaging namespace executes the MSMQ programming operation. This namespace has two main objects:
Message msg = null;MessageQueuemq = null;try{msg = new Message();msg.Priority = MessagePriority.Normal;if (!MessageQueue.Exists(@".\Private$\TechRepublic")){mq = MessageQueue.Create(@".\Private$\TechRepublic");}else{mq = new MessageQueue(@".\Private$\TechRepublic");}msg.Label = "Test Message";msg.Body = "This is only a test";mq.Send(msg);Console.WriteLine("Message sent.");}catch (System.Messaging.MessageQueueException ex){Console.WriteLine("MSMQ Error: " + ex.ToString());}catch (Exception ex){Console.WriteLine("Error: " + ex.ToString());}finally{mq.Close();}
The C # code in creates a new private MSMQ Message Queue (if no queue exists) and creates a message at the same time.
The Code uses the exists method of the messagequeue class to determine whether a private queue named techrepublic exists. If yes, it uses the messagequeue object of the existing queue example; otherwise, a new queue is created.
The new message object is used to send a message to the queue. Its label attribute specifies the Message Title displayed on the MSMQ console. Its subject contains the project content stored in the queue. In this case, I only send text, but you can use any type of object. The send method of the messagequeue class sends messages to the queue.
Dim mq As MessageQueueDim msg As MessageTrymsg = New Messagemsg.Priority = MessagePriority.NormalIf Not (MessageQueue.Exists(".\Private$\TechRepublic2")) Thenmq = MessageQueue.Create(".\Private$\TechRepublic2")Elsemq = New MessageQueue(".\Private$\TechRepublic2")End Ifmsg.Label = "Test Message"msg.Body = "This is only a test"mq.Send(msg)Console.WriteLine("Message sent.")Catch ex As MessageQueueExceptionConsole.WriteLine("MSMQ Error: " + ex.ToString())Catch ex As ExceptionConsole.WriteLine("Error: " + ex.ToString())Finallymq.Close()End Try
Is the corresponding VB. NET code.
The next step is to read messages from the queue. This is a simple process. Just use the receive method of the messagequeue class. If a message exists in the queue, the receive method returns a message object; otherwise, it waits for a message to appear (you can set a time period ). To restore an object from a queue, you must know its type in advance.
The formatter attribute of the messagequeue class allows you to easily specify the type of the recovered object. The following simple example only uses text, so it applies system. String. In
Message msg = null;MessageQueuemq = null;try{mq = new MessageQueue(@".\Private$\TechRepublic");msg = mq.Receive(new TimeSpan(0, 0, 3));msg.Formatter = new XmlMessageFormatter(new String[] {"System.String,mscorlib"});mq.Receive();Console.WriteLine(msg.Label.ToString() + " -- " + msg.Body.ToString());}catch (System.Messaging.MessageQueueException ex){Console.WriteLine("MSMQ Error: " + ex.ToString());}catch (Exception ex){Console.WriteLine("Error: " + ex.ToString());}finally{mq.Close();}
The C # Code reads messages from the test queue.
The timespan object submitted to the receive method specifies the system wait time when an exception occurs. Next, set the formatter method in this example. The object is converted into a string to read the text stored previously. The receive method reads a message from the queue. Its value is displayed on the console. In the last part of the try block, the queue is disabled.
Easily apply messages
MSMQ combines the system. messaging namespaces of windows and. net, allowing you to conveniently use messages in. NET applications. Message provides a powerful tool for sending and receiving messages (data) asynchronously in enterprise applications.