RABBITMQ Basic Learning Notes (C # code example)

Source: Internet
Author: User
Tags message queue switches rabbitmq

First, the definition:

MQ is MessageQueue, the abbreviation for Message Queuing (a popular open source Message Queuing system, developed using Erlang language). MQ is an application-to-application communication method. Applications communicate by reading the messages written to the team and out of the queue, without needing a dedicated connection to link them.

Messaging is a technique that is typically applied to remote procedure calls by communicating between programs by sending data in a message, rather than by calling each other directly.

Queuing refers to an application communicating through a queue. The application queue avoids receiving and sending data at the same time.

Second, features:

MQ is the representative of the consumer-producer model. One end writes messages to the message queue, and the other end can read or subscribe to messages in the queue. MQ follows the AMQP protocol (Advanced Message Queuing protocol: making it possible to comply with the specification's full-featured interoperability of client applications and messaging middleware servers) and products.

Third, Application:

When using MQ, we do not need to return information in real time. Gets information and returns information for asynchronous processing. For example: In the project, we need to use can bus in the car system to get the information of the car in real time, but it is not necessary to return the information to the car. For example, get the tyre pressure of the car, but we do not need to give the car a return information or result.

C # project to use RabbitMQ to obtain real-time data, you need to install the client's library file: RabbitMQ.Client.dll, as follows:

http://download.csdn.net/detail/qq_30507287/9599941

Four, the structure of the RABBITMQ diagram:

V. Basic concepts:

Broker: Message Queuing server entity.

Exchange: A message switch that specifies the rules by which messages are routed to which queue. Can be understood as a program with a routing table. Each message has a property that becomes a routing key (routing key). The switch has a series of bindings (binding) that are routing rules.

Queue: A message queue carrier in which each message is put into one or more queues. The message stays inside until a client (consumer) connects to the queue and takes it away. A queue is created by a consumer through a program.

Binding: Binds Exchange and queue according to routing rules.

Routing key: The routing keyword, exchange messages are delivered based on this keyword.

Vhost (VirtualHost): Virtual host, a broker can open multiple Vhost, as a separate user permissions separation.

Producer: The message producer is the program that delivers the message.

Consumer: The message consumer is the program that receives the message.

Channel: The message channels, in each connection of the client, multiple channels can be established, each channel represents a session task.

Note 1: The more important four: vhost,exchange,queue,binding. A virtual host holds a set of switches, queues, and bindings.

NOTE 2: Consumer programs are responsible for creating switches (more than one)? Because each switch executes in its own independent process, adding multiple switches increases the number of processes that can take advantage of the CPU cores on the server to improve efficiency. (On a 8-core service, 5 cores can be used to create 5 switches, and the remaining 3 are used to process messages.) )

Note 3: A binding is a routing rule that connects switches and queues based on a routing key.

Six, the use of Message Queuing process is as follows:

(1) The client connects to the Message Queuing server and opens a channel.

(2) The client declares an exchange and sets the related properties.

(3) The client declares a queue and sets the related properties.

(4) The client uses Routingkey to establish a good binding relationship between Exchange and queue.

(5) Clients post messages to exchange.

Note: When Exchange receives a message, it routes messages to one or more queues based on the key of the message and the binding that has been set.

Vii. Types of Exchange (switch types):

1) Direct switch:

(Process routing key) is delivered entirely according to key. A queue needs to be bound to the switch, requiring the message to exactly match a specific routing key.

Binding set Routing key to "ABC", then the client submits the message, only the key is set to "ABC" will be posted to the queue.

2) Topic Switch:

(Matching a Routing key to a pattern) the queue needs to be bound to a pattern, and the key will be delivered after a pattern match.

"#" matches one or more words, "*" matches exactly one word. "abc.#" matches "Abc.def.ghi", "abc.*" matches only "Abc.def".

3) fanout switch: (does not handle the routing key) does not require a key value, in broadcast mode, when the message comes in, it is posted to all the queues that are bound to the switch.

Viii. Persistence of queue messages:

1, why will there be persistent?

It takes a lot of time to create queues, switches, and bindings, and queues, switches, and bindings are emptied if the server is accidentally or externally faulted. RABBITMQ will empty the original after restarting. As a result, a flag durable is specified to control when the queue and switch are created. Of course, durable means that the queue and switch containing the flag will be re-established after the reboot, instead of resuming after the message in the queue restarts.

2. Message Queue persistence consists of 3 parts:

(1) Exchange persistence, at the time of declaration, specify durable = 1;

(2) Queue persistence, at the time of declaration, specify durable = 1;

(3) Message persistence, specify delivery_mode=> 2 on delivery (1 is non-persistent, 2 means persistent, persistent);

If both Exchange and queue are persisted, then the binding between them is persistent. If there is a persistence between Exchange and queue, a non-persisted, binding is not allowed.

Description: Delivery mode (delivery mode)

3. Persistence of bindings (binding):

Bindings cannot be set durable when they are created, so the persistence of bindings is accomplished by queues and switches. If you bind a durable queue and a durable switch, RABBITMQ automatically retains this binding. As long as one of the queues and switches is not durable, the bindings that depend on them are automatically deleted.

Ix.. net/c# in the client RABBITMQ

(1) Main namespaces, interfaces and classes

The core API interfaces and classes are defined in the Rabbitmq.client namespace.

Using Rabbitmq.client;

The core interfaces and classes are:

Imodel:representsan AMQP 0-9-1 Channel, and provides most of the operations (Protocol methods). Represents the channel that provides the Protocol method.

Iconnection:represents an AMQP 0-9-1 connection

Connectionfactory:constructs Iconnection Instances

Ibasicconsumer:represents a message consumer represents the consumer of the messages.

Other interfaces and classes:

Defaultbasicconsumer:commonly used base class for consumers

Other common rabbitmq.client namespaces include the following:

RabbitMQ.Client.Events:various Events and event handlers that is part of the Client library,including eventingbasicconsum Er, a consumer implementation built around c#event handlers.

RabbitMQ.Client.Exceptions:exceptions visible to the user.

(2) Connection agent

To connect to RABBITMQ, you must instantiate a connectionfactory and configure on a rabbitmq to a host, virtual machine, or a certified device. The following code is a connection to the RABBITMQ node on the host.

ConnectionFactory factory = Newconnectionfactory ();

Factory. Uri = "Amqp://user:[email protected]:p ort/vhost";

Iconnection conn = Factory. CreateConnection ();

You can then use the Iconnection interface to open a channel:

IModel channel = conn. Createmodel ();

(3) Using switches and queues

Model. Exchangedeclare (Exchangename,exchangetype.direct);

Model. Queuedeclare (Queuename,false,false,false,null);

Model. Queuebind (QueueName, Exchangename, routingkey,null);

(4) Post a message

Use the switch (Exchange) to send messages using the Imodel.basicpublish

Byte[]messagebodybytes = System.Text.Encoding.UTF8.GetBytes ("Hello, world!");

Model. Basicpublish (Exchangename, routingkey,null,messagebodybytes);

For details, you can use overloaded variables to specify flags or special message properties:

Byte[]messagebodybytes = System.Text.Encoding.UTF8.GetBytes ("Hello, world!");

Ibasicproperties props = model. Createbasicproperties ();

Props. ContentType = "Text/plain";

Props. DeliveryMode = 2;

Model. Basicpublish (Exchangename,routingkey, props, messagebodybytes);

To send a custom message:

Byte[]messagebodybytes = System.Text.Encoding.UTF8.GetBytes ("Hello, world!");

Ibasicproperties props = model. Createbasicproperties ();

Props. ContentType = "Text/plain";

Props. DeliveryMode = 2;

Props. Headers = new dictionary<string,object> ();

Props. Headers.add ("Latitude", 51.5252949);

Props. Headers.add ("Longitude",-0.0905493);

Model. Basicpublish (Exchangename, Routingkey, props, messagebodybytes);

X. (C # instance resolution) Producer Application parsing

(1) from the Producer application point of view, establish a connection using the default settings, create a connection, and create a channel:

Namespaceproducer    {        classprogram        {            staticvoidmain (string[] args)            {               var connectionfactory =newconnectionfactory ();               Iconnection connection =connectionfactory.createconnection ();               IModel channel = connection. Createmodel ();}}}    

  

(2) declaring a switch and publishing a message

Channel. Exchangedeclare ("Direct-exchange-example", exchangetype.direct);

The second parameter table names the type of the parameter, optionally direct,fanout,topic, or headers.

(3) Call the method, produce a return value, call Dosomethinginteresting () in this example, and return the value of a string.

String value = Dosomethinginteresting ();

(4) dosomethinginteresting () implementation can return a new GUID string value

Staticstringdosomethinginteresting ()

{

Returnguid.newguid (). ToString ();

}

(5) Use the return value to create a log message:

String LogMessage =string. Format ("{0}: {1}", traceeventtype.information, value);

(6) Convert the log message to a byte array and publish the message to the new switch:

Byte[]message =encoding.utf8.getbytes (logmessage);

Channel. Basicpublish ("Direct-exchange-example", "", null,message);

(7) Finally, to close the channel and connect

Channel. Close ();

Connection. Close ();

Xi. (C # instance resolution) consumer application parsing

(1) Create a consumer like the generator

Using Rabbitmq.client; namespace consumer{    classprogram    {        staticvoidmain (string[] args)        {            varconnectionfactory = new ConnectionFactory ();            Iconnection connection = Connectionfactory.createconnection ();            IModel channel = connection. Createmodel ();            Channel. Exchangedeclare ("Direct-exchange-example", Exchangetype.direct);}}    

  

(2) Declare a queue to bind the switch, the queue name is "logs"

Channel. Queuedeclare ("Logs", false,false,true,null);

(3) Bind "logs" queue, using Queuebind ()

Channel. Queuebind ("Logs", "Direct-exchange-example", "" ");

(4) Declaring consumer objects

VAR consumer =newqueueingbasicconsumer (channel)

(5) Push message

Channel. Basicconsume ("Logs", True,consumer);

(6) Any message will be automatically retrieved and placed in the local memory queue of the memory queue.

var EventArgs = (Basicdelivereventargs) consumer. Queue.dequeue ();

Convert EventArgs to string and print output

var message =encoding.utf8.getstring (Eventargs.body);

Console.WriteLine (message);

(7) Close the channel and connect

Channel. Close ();

Connection. Close ();

12. (C # instance code) production-full code for consumption mode

(1)

using system;using system.diagnostics;using System.Text;using System.threading;using rabbitmq.client;            Namespace producer{Classprogram {staticvoidmain (string[] args) {thread.sleep (1000);            Varconnectionfactory = new ConnectionFactory ();            Iconnection connection = Connectionfactory.createconnection (); IModel channel = connection.            Createmodel (); Channel.            Exchangedeclare ("Direct-exchange-example", exchangetype.direct);            StringValue = Dosomethinginteresting (); Stringlogmessage = string.             Format ("{0}:{1}", Traceeventtype.information,value);           Byte[]message = Encoding.UTF8.GetBytes (logmessage); Channel.            Basicpublish ("Direct-exchange-example", "", null,message); Channel.           Close (); Connection.        Close (); } staticstringdosomethinginteresting () {Returnguid.newguid ().        ToString (); }    }}

(2)

Using system;using system.text;using rabbitmq.client;using RabbitMQ.Client.Events; Namespace consumer{Classprogram {staticvoidmain (string[] args) {varconnectionfactory = n            EW ConnectionFactory ();            Iconnection connection = Connectionfactory.createconnection (); IModel channel = connection.            Createmodel (); Channel.           Exchangedeclare ("Direct-exchange-example", exchangetype.direct); Channel.           Queuedeclare ("Logs", false,false,true,null); Channel.             Queuebind ("Logs", "Direct-exchange-example", "" ");           Varconsumer = new Queueingbasicconsumer (channel); Channel.             Basicconsume ("Logs", True,consumer); Vareventargs = (basicdelivereventargs) consumer.             Queue.dequeue ();            Stringmessage = Encoding.UTF8.GetString (eventargs.body);            Console.WriteLine (message); Channel.           Close (); Connection.            Close ();        Console.ReadLine (); }    }}

Reproduced:

http://blog.csdn.net/qq_30507287/article/details/52176603

RABBITMQ Basic Learning Notes (C # code example)

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.