Home Backend Development C#.Net Tutorial Introduction to Message Queue and its use

Introduction to Message Queue and its use

Dec 20, 2016 am 09:25 AM

Using MSMQ (Microsoft Message Queue), application developers can easily communicate with applications quickly and reliably by sending and receiving messages. Message processing provides you with guaranteed message delivery and a reliable, fail-safe way to perform many business processes.

MSMQ, like XML Web Services and .Net Remoting, is a distributed development technology. However, when using XML Web Services or .Net Remoting components, 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, temporarily saving the message in the client's message queue, and then sending it to the server for processing when it is online later.

Obviously, MSMQ is not suitable for situations where the client requires a timely response from the server. MSMQ interacts with the server in an asynchronous manner, so there is no need to worry about waiting for the server to process for a long time.

Although XML Web Services and .Net Remoting both provide the [OneWay] attribute to handle asynchronous calls, which is used to solve the problem of long method calls on the server side that hinder the client side for a long time. However, it cannot solve the problem of a large number of Client loads. At this time, the Server accepts requests faster than it processes them.

Generally, the [OneWay] attribute is not used in specialized messaging services.

1. Basic terms and concepts

"Message" is a unit of data transmitted between two computers. Messages can be very simple, containing only text strings, or they can be more complex, possibly containing embedded objects.

The message is sent to the queue. A "message queue" is a container that saves messages during their transmission. The message queue manager acts as a middleman when relaying messages from its source to its destination. The main purpose of a queue is to provide routing and guarantee the delivery of messages; if the recipient is unavailable when the message is sent, the message queue holds the message until it can be successfully delivered.

"Message Queuing" is Microsoft's messaging technology that provides message processing and message queuing functionality to any application on any combination of computers with Microsoft Windows installed, regardless of whether the computers are on the same network or not. online at the same time.

A "message queue network" is any group of computers that can send messages back and forth to each other. Different computers in the network play different roles in ensuring that messages are processed smoothly. Some of them provide routing information to determine how to send messages, some hold important information about the entire network, and some just send and receive messages.

During Message Queuing installation, the administrator determines which servers can communicate with each other and sets special roles for specific servers. The computers that make up this Message Queuing network are called sites, and they are connected to each other through site links. Each site link has an associated "cost," which is determined by the administrator and indicates how often messages are delivered through the site link.

The "Message Queuing" administrator also sets up one or more computers as "routing servers" in the network. The routing server determines how to deliver the message by looking at the cost of each site link to determine the fastest and most efficient way to deliver the message through multiple sites.

2. Queue Type

There are two main queue types: queues created by you or other users on the network and system queues.

User-created queues may be any of the following:

"Public queues" are replicated throughout the Message Queuing network and potentially accessible by all sites connected to the network.

"Private Queues" are not published across the entire network. Instead, they are only available on the local computer where they reside. Private queues can only be accessed by applications that know the queue's full pathname or label.

A “Management Queue” contains messages acknowledging receipts for messages sent in a given “Message Queue” network. Specifies the management queue (if any) you want the MessageQueue component to use.

The "response queue" contains the response messages returned to the sending application when the target application receives the message. Specifies the response queue (if any) you want the MessageQueue component to use.

System-generated queues are generally divided into the following categories:

"Journal Queue" optionally stores copies of messages sent and copies of messages removed from the queue. A single journal queue on each Message Queuing client stores copies of messages sent from that computer. A separate journal queue is created on the server for each queue. This journal tracks messages removed from this queue.

The "Dead Letter Queue" stores copies of messages that cannot be delivered or have expired. If the expired or undeliverable message is a transactional message, it is stored in a special dead-letter queue, called a "transactional dead-letter queue." Dead letters are stored on the same computer as the expired messages. For more information about timeout periods and expired messages, see Default Message Properties.

The "report queue" contains messages indicating the route the message took to reach its destination, and can also contain test messages. There can be only one report queue per computer.

"Private system queues" are a series of dedicated queues that store management and notification messages required by the system to perform message processing operations.

Most of the work done in the application involves accessing public queues and their messages. However, depending on your application's logging, acknowledgment, and other special processing needs, you are likely to use several different system queues in day-to-day operations.

3. Synchronous vs. Asynchronous Communication

Queue communication is inherently asynchronous, because sending messages to the queue and receiving messages from the queue are completed in different processes. Additionally, receive operations can be performed asynchronously, since the person who wants to receive the message can call the BeginReceive method on any given queue and then immediately continue with other tasks without waiting for a reply. This is very different from what people know as "synchronous communication."

In synchronous communication, the sender of the request must wait for a response from the intended recipient before performing other tasks. The time the sender waits depends entirely on the time it takes the receiver to process the request and send the response.

4. Interacting with Message Queues

Message processing and messaging provide a powerful and flexible mechanism for inter-process communication between server-based application components. They have several advantages over direct calls between components, including:

Stability - component failure affects the message much less than direct calls between components, because the message is stored in the queue and remains there, until properly handled. Message processing is similar to transaction processing in that message processing is guaranteed.

Message Priority – More urgent or important messages can be received before less important messages, thus ensuring adequate response time for critical applications.

Offline Capability - When messages are sent, they can be sent to a temporary queue and remain there until successfully delivered. Users can continue operations when access to the required queue is unavailable for any reason. Meanwhile, other operations can continue as if the message has been processed, because message delivery is guaranteed when the network connection is restored.

Transactional message processing — Couples multiple related messages into a single transaction, ensuring that messages are delivered in order, delivered only once, and can be successfully retrieved from their destination queues. If any errors occur, the entire transaction will be canceled.

Security — The message queuing technology on which the MessageQueue component is based uses Windows security to protect access control, provide auditing, and encrypt and authenticate messages sent and received by the component.

5. Write a simple Message Queue program in .Net environment

(1) Install Message Queuing Services first

Install MSMQ through Control Panel, "Add/Remove Programs" - "Add/Remove Windows Components" steps .

MSMQ can be installed in workgroup mode or domain mode. If the installer does not find a server running Message Queuing that provides directory services, you can only install in workgroup mode. Message Queuing on this computer only supports the creation of private queues and the creation of shared queues with other computers running Message Queuing. direct connection.

(2) Configure MSMQ

Open Computer Management – ​​Message Queuing, create MSMQDemo queue under Private Queues

(3) Write code - simple demonstration of MSMQ objects

The MessageQueue class is around the "Message Queue" Package. The MessageQueue class provides a reference to the Message Queue queue. You can specify a path to an existing resource in the MessageQueue constructor, or you can create a new queue on the server. Before calling Send, Peek, or Receive, a new instance of the MessageQueue class must be associated with an existing queue.

MessageQueue supports two types of message retrieval: synchronous and asynchronous. The synchronous Peek and Receive methods cause the process thread to wait for a specified interval for new messages to arrive on the queue. The asynchronous BeginPeek and BeginReceive methods allow the main application task to continue execution in a separate thread before the message arrives on the queue. These methods work by using callback objects and state objects to communicate information between threads.

// Send Message

private void btnSendMessage_Click(object sender, System.EventArgs e)

{

                                                   ​Queue(".\Private$ \MSMQDemo");

// Create message

System.Messaging.Message message = new System.Messaging.Message();

message.Body = txtMessage.Text.Trim();

       message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] {typeof(string)});

 

       // Put message into queue

       queue.Send(message);

}

 

// Receive Message

private void btnReceiveMessage_Click(object sender, System.EventArgs e)

{

       // Open queue

       System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(".\Private$\MSMQDemo");

 

       // Receive message, 同步的Receive方法阻塞当前执行线程,直到一个message可以得到

       System.Messaging.Message message = queue.Receive();

       message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] {typeof(string)});

       txtReceiveMessage.Text = message.Body.ToString();

}


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

What is the difference between char and unsigned char What is the difference between char and unsigned char Apr 03, 2025 pm 03:36 PM

char and unsigned char are two data types that store character data. The main difference is the way to deal with negative and positive numbers: value range: char signed (-128 to 127), and unsigned char unsigned (0 to 255). Negative number processing: char can store negative numbers, unsigned char cannot. Bit mode: char The highest bit represents the symbol, unsigned char Unsigned bit. Arithmetic operations: char and unsigned char are signed and unsigned types, and their arithmetic operations are different. Compatibility: char and unsigned char

Common errors and ways to avoid char in C language Common errors and ways to avoid char in C language Apr 03, 2025 pm 03:06 PM

Errors and avoidance methods for using char in C language: Uninitialized char variables: Initialize using constants or string literals. Out of character range: Compare whether the variable value is within the valid range (-128 to 127). Character comparison is case-insensitive: Use toupper() or tolower() to convert character case. '\0' is not added when referencing a character array with char*: use strlen() or manually add '\0' to mark the end of the array. Ignore the array size when using char arrays: explicitly specify the array size or use sizeof() to determine the length. No null pointer is not checked when using char pointer: Check whether the pointer is NULL before use. Use char pointer to point to non-character data

See all articles