C # implementing asynchronous Message Queuing

Source: Internet
Author: User
Message Queuing

Message Queuing (English: The message queue) is an inter-process communication or a method of communication between different threads of the same process, and the software's storage is used to process a series of inputs, usually from the user. Message Queuing provides an asynchronous communication protocol in which the records in each storage column contain detailed information about the time taken, the type of input device, and the specific input parameters, which means that the sender and receiver of the message do not need to communicate with the message queue at the same time. The message is saved in the queue until the recipient retrieves it.

Simply put, the queue is the storage of the command we need to handle but not in time to get its processing results;

Realize

In fact, message queues are often stored in a linked list structure. A process that has permissions can write or read messages to a message queue.

Currently, there are many message queues with many open source implementations, including JBoss Messaging, Joram, Apache ActiveMQ, Sun Open message queue, Apache Qpid, and Httpsqs.

Advantages, Disadvantages

The message queue itself is asynchronous, which allows the recipient to retrieve the message after the message is sent for a long time, which is different from most communication protocols. For example, the HTTP protocol used in WWW is synchronous because the client must wait for the server to respond after making the request. However, in many cases we need asynchronous communication protocols. For example, a process notifies another process that an event has occurred, but does not need to wait for a response. But the asynchronous nature of Message Queuing also creates the disadvantage that the recipient must poll the message queue to receive the most recent message.

Message Queuing can deliver more information than a signal. Message Queuing provides formatted data compared to pipelines, which can reduce the workload for developers. However, Message Queuing still has a size limit.

Reading queue messages

There are two main (1) service-side push; (2) client pull;

Pull: Mainly client timed polling take away message processing;

Push: Proactive notification of Subscribers through event subscription processing;

Storage of messages

It is simple to store through a memory list, or DB, such as Redis, and can be persisted to a local file;

How to guarantee the consistency of asynchronous processing

Although the main purpose of the queue is to implement message storage, asynchronous calls and implementations. But if you want to deal with message consistency, the good way is to differentiate the business process sequence, such as Operation Master-slave DB, the main responsible for writing, from the responsible reading, we do not have the opportunity to write immediately after the database to get the results you want, and we need to use the middle State, When more than one intermediate state conforms to the calling result until the business time is processed, the exception message is persisted for the next operation;

On the Code

Establishing messages against the core queue

{public delegate void Messagequeueeventnotifyhandler (Message.basemessage Message); public class Messagequeue:queue<basemessage> {public static MessageQueue Globalqueue = new MessageQueue ()         ;        Private Timer timer = new timer ();            Public MessageQueue () {this.timer.Interval = 5000;            this.timer.Elapsed + = Notify;        This.timer.Enabled = true; private void Notify (object sender, Elapsedeventargs e) {lock (this) {if (this). Count > 0) {//this.messagenotifyevent.getinvocationlist () [0]. DynamicInvoke (this.                    Dequeue ()); var message = this.                    Dequeue ();                This.messagenotifyevent (message);        }}} private Messagequeueeventnotifyhandler messagenotifyevent; Public event Messagequeueeventnotifyhandler Messagenotifyevent {add {this.messagenotifyevent +           = value; } remove {if (this.messagenotifyevent! = null) {this.messagenotifyevent-                = value; }            }        }    }}

Event handling

Public Const string Ordercodeprefix = "P";        public void Submit (Message.basemessage message)        {            Order order = Message. Body as Order;             if (order. Ordercode.startswith (Ordercodeprefix))            {                System.Console.WriteLine ("This is the correct order to start with ({0}): {1}", Ordercodeprefix,order. Ordercode);            }            else {                System.Console.WriteLine ("This is a wrong order, not starting with ({0}): {1}", Ordercodeprefix,order. Ordercode);            }        }

Personalized processing According to the specific business;

Append messages to the queue by proxy

public class Orderserviceproxy:iorderservice    {public        void Submit (Message.basemessage Message)        {            MessageQueue.MessageQueue.GlobalQueue.Enqueue (message);        }    }

Client Calls

OrderService OrderService = new OrderService ();            MessageQueue.MessageQueue.GlobalQueue.MessageNotifyEvent + = Orderservice.submit;             var orders = new List<order> () {                New Order () {ordercode= "P001"},                New Order () {ordercode= "P002"},                new Order () {ordercode= "B003"}            };             Orderserviceproxy proxy = new Orderserviceproxy ();            Orders. ForEach (order = proxy. Submit (New Message.basemessage () {body=order}));             Console.ReadLine ();

This satisfies the event binding and triggers the personalization processing, at the same time achieves the message asynchronous goal, hoped that the more detailed extension uses in later project.

The above is the C # implementation of asynchronous Message Queuing content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.