Learn WCF (1) with me -- MSMQ Message Queue

Source: Internet
Author: User
Tags msmq

I. Introduction

Windows Communication Foundation (WCF) is a unified programming model provided by Microsoft to build service-oriented applications. The service model provides serialization functions that support loose coupling and version management, and provides Message Queue (MSMQ), COM +, Asp.net Web Services ,. net remoting and other existing Microsoft Distributed System Technologies. Using the WCF platform, developers can easily build service-oriented applications (SOA ). It can be considered that WCF refers to the existing distributed technology (MSMQ ,. net remoting and Web Services) integration and expansion. In this case, we need to first understand the previous distributed technology. Only in this way can we better understand the benefits of WCF. Today I will share with you the MSMQ distributed technology.

II. Introduction to MSMQ

The full name of MSMQ is Microsoft Message Queue-Microsoft Message Queue. It is an asynchronous transmission mode that enables communication between 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.

2.1 How MSMQ works

The implementation principle of MSMQ is: the message sender puts the information he wants to send into a container and saves it to the message queue in a public space of the system, the local or remote message receiving program then extracts the messages sent to it from the queue for processing.

A message queue is a public storage space that can exist in memory or physical files. Therefore, messages are sent in two ways: Express Delivery Mode and recoverable mode. The difference is that messages are stored in different locations. For the sake of fast message delivery, messages are stored in the memory instead of on the physical disk, in order to obtain high processing capability, while the recoverable mode writes messages to the physical disk in each step of the transfer process, in this way, when the machine that stores the Message Queue restarts after a fault occurs, the sent message can be restored to the status before the fault is sent for better message recovery capabilities. Message queues can be placed on the sender and receiver machines, or separately on another machine. In addition, with the message queue mechanism, the sender does not have to worry about factors such as the start and failure of the receiver. As long as the message is successfully sent out, the processing is complete, in fact, the other party may not even be on the machine, or the actual message delivered to the other party may be on the next day. The MSMQ mechanism is similar to the QQ message transmission mechanism. Demonstrate the implementation principle of MSMQ.

MSMQ has two main concepts.

    • One is message: message is the message to be transmitted by both parties. It can be text, images, videos, etc. A message contains the sender and receiver IDs. Only the specified user can obtain the message.
    • One is queue: the storage space used to store messages. MSMQ mainly includes the following queue types:
      • Public queue: replication across the message queue network, which may be accessed by all sites connected to the network. Path format: Machine name \ queue name
      • Dedicated Queue (or private Queue): It is not released across the network. 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. Path format: Machine name \ private $ \ queue name
      • Log queue: contains the message receipt message sent in the specified message queue ". Path format: Machine name \ queue name \ journal $
      • Response queue: contains the response message returned to the application when the target application receives the message, including the machine log queue, machine dead message queue, and machine transaction dead message queue.
        • The format of the machine log queue is: Machine name \ journal $;
        • The format of the machine dead message queue is: Machine name \ deadletter $;
        • The format of the machine channel dead message queue is: Machine name \ xactdeadletter $.


2.2 queue reference

After a messagequeue instance is created, it indicates which queue to communicate with. net. There are three methods to access the specified message queue in. Net:

    • The path of the message queue is uniquely determined by the machine name and queue name. Therefore, you can use the Message Queue path to specify the message queue in use.
    • The format name is the unique identifier generated by MSMQ when a message queue is created. It is a guid automatically generated by the queue manager rather than specified by the user.
    • Label is a meaningful name specified by the message manager when a message queue is created.


Iii. Advantages and Disadvantages of Message Queue

The advantage of message queue is that, due to asynchronous communication, the sender and receiver can execute the remaining Code while waiting for the other party to return a successful message, greatly improving the processing capability; in the process of information transmission, it is capable of fault recovery; MSMQ message transmission mechanism makes it possible for both parties to communicate with different physical platforms.

The disadvantage of message queue is that the client does not need to interact with the server in real time. When a large number of requests are sent, the response may be delayed.

4. Use MSMQ to develop distributed application 4.1 environment preparation

To. to develop MSMQ on the net platform, you need to install message queue. You need to open Control Panel> program> enable or disable the WINDOWS function and check all options of Message Queue Service, as shown in the following figure:

After selecting the check box, click OK. You can view the following figure on my computer-> Management-> services and applications-> Message Queue:

The figure above indicates that you have successfully configured the MSMQ development environment. You can use Visual Studio for development. Note that the corresponding queue type must be successfully installed for the operation code of a queue of a specific type.

4.2 Use MSMQ to develop distributed applications

First, implement the server. Create a console project and add system. Messaging Reference, because all the Message Queue classes are encapsulated in the system. messaging. dll collection. The specific server code is as follows:

 1 using System; 2 using System.Messaging; 3  4 namespace MSMQServer 5 { 6     class Program 7     {   8         static void Main(string[] args) 9         {10             // 创建一个公共队列,公共队列只能创建在域环境里11             //if (!MessageQueue.Exists(@".\LearningHardMSMQ")) // 判断此路径下是否已经有该队列12             //{13             //    using (MessageQueue mq = MessageQueue.Create(@".\LearningHardMSMQ"))14             //    {15             //        mq.Label = "LearningHardQueue"; // 设置队列标签16             //        Console.WriteLine("已经创建了一个公共队列");17             //        Console.WriteLine("路径为:{0}", mq.Path);18             //        Console.WriteLine("队列名字为:{0}", mq.QueueName);19             //        mq.Send("MSMQ Message", "Leaning Hard"); // 发送消息20             //    }21             //}22 23             //if (MessageQueue.Exists(@".\Private$\LearningHardMSMQ"))24             //{25                   // 删除消息队列26             //    MessageQueue.Delete(@".\Private$\LearningHardMSMQ");27             //}28             // 创建一个私有消息队列29             if (!MessageQueue.Exists(@".\Private$\LearningHardMSMQ"))30             {31                 using (MessageQueue mq = MessageQueue.Create(@".\Private$\LearningHardMSMQ"))32                 {33                     mq.Label = "LearningHardPrivateQueue"; 34                     Console.WriteLine("已经创建了一个私有队列");35                     Console.WriteLine("路径为:{0}", mq.Path);36                     Console.WriteLine("私有队列名字为:{0}", mq.QueueName);37                     mq.Send("MSMQ Private Message", "Leaning Hard"); // 发送消息38                 }39             }40 41             // 遍历所有的公共消息队列42             //foreach (MessageQueue mq in MessageQueue.GetPublicQueues())43             //{44             //    mq.Send("Sending MSMQ public message" + DateTime.Now.ToLongDateString(), "Learning Hard");45             //    Console.WriteLine("Public Message is sent to {0}", mq.Path);46             //}47            48             if (MessageQueue.Exists(@".\Private$\LearningHardMSMQ")) 49             {50                 // 获得私有消息队列51                 MessageQueue mq = new MessageQueue(@".\Private$\LearningHardMSMQ");52                 mq.Send("Sending MSMQ private message" + DateTime.Now.ToLongDateString(), "Leaning Hard");53                 Console.WriteLine("Private Message is sent to {0}", mq.Path);54             }55 56             Console.Read();57         }58     }59 }

The server code must note that public queues can only be created in the domain environment. Because my PC is not added to the domain environment, public queues cannot be created, from the beginning of the message queue, we can see that there is no public queue installed in the figure.

After the server is implemented, the client is completed. The principle of the MSMQ program is that the server sends messages to the shared message queue, and then the client extracts the messages from the shared message queue for processing. The implementation code of the specific client is as follows:

 1 using System; 2 using System.Messaging; // 需要添加System.Messaging引用 3  4 namespace MSMQClient 5 { 6     class Program 7     { 8         static void Main(string[] args) 9         {10             if (MessageQueue.Exists(@".\Private$\LearningHardMSMQ"))11             {12                 // 创建消息队列对象13                 using (MessageQueue mq = new MessageQueue(@".\Private$\LearningHardMSMQ"))14                 {15                     // 设置消息队列的格式化器16                     mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });17                     foreach (Message msg in mq.GetAllMessages())18                     {19                         Console.WriteLine("Received Private Message is: {0}", msg.Body);20                     }21 22                     Message firstmsg = mq.Receive(); // 获得消息队列中第一条消息23                     Console.WriteLine("Received The first Private Message is: {0}", firstmsg.Body);24                 }25             }26             Console.Read();27         }28     }29 }
4.3 run demo

After the above steps, we have completed the implementation of the MSMQ distributed program. Let's take a look at how to run the program to view the results.

First, you need to start the server, right-click the msmqserver project-> debug-> Start a new instance to start the server, as shown in the following steps:

After running successfully, you will go to the console interface where the message is successfully sent by the server, as shown below:

Next, run the client to obtain the message from the message queue and display it in the console. Start the client in the same way as the server, right-click msmqclient-> debug-> Start a new instance, shows the effect of the client:

It can be seen that the client has successfully obtained messages in the message queue.

The above MSMQ program requires special attention: messagequeue. receive () is used to retrieve the first message in the message queue and remove it from the message queue. (The msdn Chinese translation is incorrect. What msdn writes is not removed, but the actual results are also removed. If you run the client again, you will find that there is only one message in the message queue. The specific running effect is shown in:

V. Summary

At this point, the MSMQ content is shared, and its implementation principle of MSMQ is also very simple. In a single sentence, the server puts messages in a public place, which is called message queue, other clients can retrieve messages from this location for processing. The next chapter will share the. NET remoting, another Distributed Technology on the. NET platform.

Sample Code File: msmqsample.


Learn WCF (1) with me -- 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: 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.