. NET using RABBITMQ detailed

Source: Internet
Author: User
Tags ack rabbitmq

Preface

These days, the company storm again, last year, the company's CTO for 4, the CEO for three, this is not just a new boss, feel good, but did not do 3 months to go again, simply while the eldest brother walked to go to the time, to himself empty out, Briefly summarize the RABBITMQ used in a log service component that you just wrote and apply it in. NET combat.

Let's not talk about my log components first. Because some logs need to go to the network, some do not need to go to the Internet, but also has the performance and the business scene of many changes in which, put him aside, we only talk about the message rabbitmq.

So what is RABBITMQ, what is it used to solve, what is the performance, and how? I will explain in the following one by one, if there are errors, not to the place, but also hope that everyone is not hesitate to enlighten.

RABBITMQ Introduction

It must be mentioned that RABBITMQ is an open-source implementation of a Message Queuing protocol (AMQP) provided by LShift, written by Erlang, known for its high performance, robustness, and scalability (and therefore inherited from these advantages).

Baidu Encyclopedia to Rabbitmq elaborated also very clear, suggest go to see, also have AMQP agreement.

RABBITMQ Official website: http://www.rabbitmq.com/If you want to download the installation, you must first load the Erlang language.

RABBITMQ. NET client that can be easily obtained by entering RABBITMQ in NuGet.

RABBITMQ and other message queue comparison, there are immortal to write out. Message Queue Shootout

The test cases in this article are as follows: 1 million messages of 1k, such as the sending and receiving of each second.

If you install, RABBITMQ, he will provide an operation monitoring page, the page below, he almost provides, all operations on the RABBITMQ, and monitoring, so, you installed after yourself to look at, multi-action under.

Some nouns in rabbitmq describe the whole process of message from delivery to consumption.

From the title can see some unfamiliar English words, let us feel ignorant, even more impossible to operate, then I give you a picture you can see, perhaps to you understand these new words helpful.

After reading these nouns, then, perhaps you have no clue, then I put the message from production to consumption of the entire process to tell you, perhaps a little deeper, where exchange, and queue can be set related properties, the persistence of queues, exchanger type development.

Note: First this process is divided into three parts, 1, the client (production message queue), 2, the RABBITMQ server (responsible for routing rules binding and message distribution), 3, the client (consume messages in message queue)

Note: As can be seen from the graph, a message can go once the network is distributed to different message queues, and then consumed by multiple clients, then this process is the core mechanism of RABBITMQ, RABBITMQ routing type and consumption mode.

Types of exchange in RABBITMQ

There are 4 kinds of types, direct,fanout,topic,headers. of which headers is not commonly used, this article does not introduce, the other three kinds of types, will do a detailed introduction.

So what do these types mean? When Exchange is bound to a queue, messages are distributed to message queues according to different binding rules depending on the type of Exchang, either a message is distributed to multiple message queues or a message is distributed to a message queue. Please see below for details.

At the beginning of the introduction also to say Routingkey, this is what kind of thing? He is an identity in exchange and Message Queuing bindings. Some route types are identified by the corresponding message queue, and some route types ignore Routingkey. See below for details.

1. Exchange Type Direct

He is looking for a queue based on the name of the exchanger and the Routingkey.

Note: Messages are sent from the client and sent to the exchanger changea,routingkey to ROUTINGKEY.ZLH, so whether you send Queue1 or Queue2 a message will be saved in Queue1,queue2,queue3, Three queues in a queue. This is the routing rule for the switch's direct type. As soon as the router is found with the Routingkey bound queue, then how many queues he has, and how many queues he distributes to.

2. Exchange Type Fanout

This type ignores Routingkey, he is broadcast mode.

Note: The message is sent from the client, so long as the queue is bound to exchange, he doesn't care what your routingkey is. He distributes the message to all the queues that are bound to the Exchang.

3. Exchange Type Topic

This type of routing rule if you master it, it is quite handy, with flexibility. He does the matching according to the Routingkey setting, where there are also two wildcard characters:

*, representing any one word. For example topic.zlh.*, he can match to, Topic.zlh.one, Topic.zlh.two, TOPIC.ZLH.ABC, ....

#, representing any number of words. For example topic.#, he can match to, Topic.zlh.one, Topic.zlh.two, TOPIC.ZLH.ABC, ....

Note: This image looks messy, but he does match according to the match, and here I suggest you do the specific operation of the message queue yourself.

The operation is as follows

 public static void Producer (int value) {try {var qName = "Lhtest1";                var exchangename = "Fanoutchange1";                var ExchangeType = "Fanout";//topic, fanout var routingkey = "*";                var uri = new Uri ("amqp://192.168.10.121:5672/"); var factory = new ConnectionFactory {UserName = "123", Password = "1                ", Requestedheartbeat = 0, Endpoint = new Amqptcpendpoint (URI)}; using (var connection = factory. CreateConnection ()) {using (var channel = connection. Createmodel ()) {//sets the type of exchanger channel.                        Exchangedeclare (Exchangename, ExchangeType); Declares a queue, sets whether the queue is persisted, exclusive, and automatically deletes the channel.      Queuedeclare (QName, True, False, false, NULL);                  Bind message Queue, exchanger, Routingkey channel.                        Queuebind (QName, Exchangename, Routingkey); var properties = Channel.                        Createbasicproperties (); Queue Persistence properties.                        Persistent = true;                        var m = new Qmessage (DateTime.Now, value+ "");                        var BODY = Encoding.UTF8.GetBytes (dojson.modeltojson<qmessage> (m)); Send the Message channel.                    Basicpublish (Exchangename, Routingkey, properties, body); }}} catch (Exception ex) {Console.WriteLine (ex).            Message); }        }
Message Queuing consumption with message acknowledgment ACK

1, the consumption of Message Queuing

Note: If there is a large number of message waiting operations in a message queue, we can use multiple clients to process the message, and the distribution mechanism is to use the polling in the load balancing algorithm. The first message to a, the next message to B, the next message to a, next to the next message to B ... And so on

2, in order to ensure the security of the message, the message is guaranteed to be processed correctly before it can be deleted in the server message queue. Then RABBITMQ provides an ACK response mechanism to implement this function.

There are two ways to answer ACK: 1, auto-answer, 2, manual answer. The specific implementation is as follows.

 public static void Consumer () {try {var qName = "Lhtest1";                var exchangename = "Fanoutchange1";                var ExchangeType = "Fanout";//topic, fanout var routingkey = "*";                var uri = new Uri ("amqp://192.168.10.121:5672/"); var factory = new ConnectionFactory {UserName = "123", Password = "1                ", Requestedheartbeat = 0, Endpoint = new Amqptcpendpoint (URI)}; using (var connection = factory. CreateConnection ()) {using (var channel = connection. Createmodel ()) {channel.                        Exchangedeclare (Exchangename, ExchangeType); Channel.                        Queuedeclare (QName, True, False, false, NULL); Channel.                        Queuebind (QName, Exchangename, Routingkey); //The consumer that defines this queue queueingbasicconsumer consumer = new Queueingbasicconsumer (channel); False for manual answer, true to automatically answer channel.                        Basicconsume (QName, false, consumer); while (true) {Basicdelivereventargs ea = (Basicdelivereventargs) consume                                                       R.queue.dequeue (); byte[] bytes = ea.                            Body;                            var messagestr = Encoding.UTF8.GetString (bytes);                            var message = dojson.jsontomodel<qmessage> (MESSAGESTR); Console.WriteLine ("Receive a message, DateTime:" + message.) DateTime.ToString ("Yyyy-mm-dd HH:mm:ss") + "Title:" + message.                            Title);                            If this is an automatic answer, the following code does not need to be written. if (Convert.ToInt32 (message. Title)% 2) = = 1) {Channel. Basicack (ea. Deliverytag, FAlse);                 }}}}} catch (Exception ex) { Console.WriteLine (ex.            Message); }        }
Summarize

RABBITMQ personal feeling is relatively simple, the article may also be relatively easy to write, Oh, forgive me. If you use RABBITMQ in your development, or if you have any doubts about the development, please join the top left group and we'll discuss the study together.

Transfer from http://www.cnblogs.com/knowledgesea/p/5296008.html

. NET using RABBITMQ detailed

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.