Rabbitmq.net Applications (1)

Source: Internet
Author: User
Tags rabbitmq rabbitmq tutorial

Overview

MQ is all called the message queue, and Message Queuing (MQ) is an application-to-application communication method. RABBITMQ is a complete, reusable enterprise messaging system based on AMQP. He follows the Mozilla Public License open source agreement. AMQP (Advanced Message Queuing Protocol) is an application-layer protocol specification used by asynchronous messaging as a line-layer protocol rather than an API (for example, JMS) where AMQP clients can send and receive information regardless of the source of the message. The original purpose of AMQP is simply to provide the financial community with a message protocol that can collaborate with one another, and now the goal is to provide common building tools for the common Message Queuing architecture. Therefore, message-oriented middleware (MOM) systems, such as publish/subscribe queues, are not implemented as basic elements. There are four concepts in AMQP that are important (one virtual host holds a set of switches, queues, and bindings):

    1. virtual host, the virtual host
    2. exchangeSwitch
    3. queueQueue
    4. bindingBinding

More theoretical things to refer to (Install the Rabbit MQ Guide on Windows), the explanation for the queue is quite detailed

Install RABBBITMQ under Window

File Download and Installation

Rabbit MQ is built on the powerful Erlang OTP platform, so installing Rabbit MQ is premised on the installation of Erlang. Download the installation from the following two connections 3.2.3 version:

    1. Download and install Erlang OTP for Windows (VR16B03)
    2. Run Install Rabbit MQ Server Windows Installer (v3.2.3)

The default installed rabbit MQ listener port is 5672. Install the Erlang OTP after installing the RABBITMQ, installation by default, RABBITMQ can check the installation background services, service start and stop operations.

Activate Rabbit MQ ' s Management Plugin

With the Rabbit MQ Management plug-in, you can better visualize the status of the Rabbit MQ Server instance, open the cmd command, and CD to the installation directory (.. \rabbitmq_server-3.2.3\sbin), enter the following command to activate:

Rabbitmq-plugins Enable Rabbitmq_management

要重启服务才能生效,可以执行

net stop RabbitMQ && net start RabbitMQ

Enter the URL to open the monitoring page: http://localhost:15672 (default account and password: Guest and guest)

Configure RABBITMQ User Rights

RABBITMQ is a user right, the default is the guest password is also guest, subordinate to the administrator administrator. Now you need to configure the new user and permissions, continue to open the CMD command, CD to the installation directory Sbin:

User Action Instructions:

:: Querying Service status
Rabbitmqctl status

:: Enumerating the list of virtual hosts
Rabbitmqctl list_vhosts
:: Enumerating User lists
Rabbitmqctl list_users

:: Add user and password Rabbitmqctl add_user hao abc123:: Set permissions rabbitmqctl set_permissions yy ". *" ". *" ". *":: Assign user group Rabbitmqctl set_user_tags yy Administrator
:: Delete Guest user
Rabbitmqctl Delete_user Guest
:: Modify User password
Rabbitmqctl Change_password {username} {NEWPASSOWRD}

. NET in RABBITMQ use

1. NuGet Download rabbitmq.client third-party class library, version V3.6.5, high version conflicts with. NET Framework 4.5, RabbitMQ Client address

2, the use of RABBITMQ Clinet Class library encoding (code content has comments, here do not do a detailed explanation, the article after the complete code)

  Direct type exchange for <1>RABBITMQ

Producter Send Message code:

        <summary>///Connection Configuration///</summary> private static readonly connectionfactory R        Abbitmqfactory = new ConnectionFactory () {HostName = "192.168.1.8", Username= "Hao", password= "abc123", port= 5672        };        <summary>////Route name///</summary> const string exchangename = "Justin.exchange";        Queue name const string queuename = "Justin.queue"; public static void Directexchangesendmsg () {using (Iconnection conn = Rabbitmqfactory.createconnection ( ) {using (IModel CHANNEL = conn). Createmodel ()) {channel.                    Exchangedeclare (Exchangename, "direct", Durable:true, Autodelete:false, arguments:null); Channel.                    Queuedeclare (QueueName, Durable:true, Autodelete:false, Exclusive:false, arguments:null); Channel.              Queuebind (QueueName, Exchangename, routingkey:queuename);      var props = Channel.                    Createbasicproperties (); Props.                    Persistent = true;                    String vadata = Console.ReadLine ();                        while (Vadata! = "Exit") {var msgbody = Encoding.UTF8.GetBytes (Vadata); Channel.                                Basicpublish (Exchange:exchangename, Routingkey:queuename, Basicproperties:props, body:msgbody); Console.WriteLine (String.                        Format ("* * * Send time: {0}, send complete, enter exit Exit message Send", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"));                    Vadata = Console.ReadLine (); }                                   }            }        }

   

Customer receives message code:

        <summary>///Connection Configuration///</summary> private static readonly connectionfactory R Abbitmqfactory = new ConnectionFactory () {HostName = "192.168.1.8", UserName = "Hao", Password = "abc123", Por        t = 5672};        <summary>////Route name///</summary> const string exchangename = "Justin.exchange";        Queue name const string queuename = "Justin.queue"; public static void Directacceptexchange () {using (Iconnection conn = Rabbitmqfactory.createconnection () ) {using (IModel CHANNEL = conn. Createmodel ()) {channel.                    Exchangedeclare (Exchangename, "direct", Durable:true, Autodelete:false, arguments:null); Channel.                    Queuedeclare (QueueName, Durable:true, Autodelete:false, Exclusive:false, arguments:null); Channel.     Queuebind (QueueName, Exchangename, routingkey:queuename);               while (true) {Basicgetresult msgresponse = channel.                        Basicget (QueueName, noack:true); if (msgresponse! = null) {var msgbody = Encoding.UTF8.GetString (msgresp Onse.                            Body); Console.WriteLine (String.                        Format ("* * * Receive time: {0}, message content: {1}", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"), msgbody)); }//basicgetresult MsgResponse2 = Channel.                        Basicget (QueueName, Noack:false); Process message ...//channel.                        Basicack (Msgresponse2.deliverytag, Multiple:false);                    System.Threading.Thread.Sleep (Timespan.fromseconds (1)); }                }            }        }

  

However, this processing is slower because the loop thread waits. The efficient way to receive messages can be processed using eventingbasicconsumer for message processing, with the following changes in the code:

        public static void Directacceptexchangeevent () {using (Iconnection conn = Rabbitmqfactory.creat Econnection ()) {using (IModel CHANNEL = conn. Createmodel ()) {//channel.                    Exchangedeclare (Exchangename, "direct", Durable:true, Autodelete:false, arguments:null); Channel.                    Queuedeclare (QueueName, Durable:true, Autodelete:false, Exclusive:false, arguments:null); Channel.                    Queuebind (QueueName, Exchangename, routingkey:queuename);                    var consumer = new Eventingbasicconsumer (channel); Consumer. Received + = (model, ea) = {var msgbody = encoding.u TF8. GetString (ea.                        Body); Console.WriteLine (String.                    Format ("* * * Receive time: {0}, message content: {1}", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"), msgbody));                    }; Channel. Basicconsume (QuEuename, Noack:true, Consumer:consumer);                    Obsolete with Eventingbasicconsumer instead of//var consumer2 = new Queueingbasicconsumer (channel); Channel.                    Basicconsume (QueueName, Noack:true, Consumer:consumer); var msgresponse = Consumer2. Queue.dequeue ();                    Blocking//var msgBody2 = Encoding.UTF8.GetString (msgresponse.body);                    Console.WriteLine ("Press any value, exit program");                Console.readkey (); }            }        }

  

Sometimes, however, consumers are not able to handle too much business at the same time, causing the queued messages that are allocated to not be processed in a timely manner, and at this point we can set the Basicqos property to tell the broker to allocate the unhandled message to other consumers at the same moment. So the place to receive the message needs to be changed slightly, the code is as follows:

public static void Directacceptexchangetask () {using (Iconnection conn = Rabbitmqfactory.createconnection ()) { using (IModel CHANNEL = conn. Createmodel ()) {//channel.            Exchangedeclare (Exchangename, "direct", Durable:true, Autodelete:false, arguments:null); Channel.            Queuedeclare (QueueName, Durable:true, Autodelete:false, Exclusive:false, arguments:null); Channel. Basicqos (prefetchsize:0, prefetchcount:1, global:false);//tell Broker to process only one message at a time//channel.            Queuebind (QueueName, Exchangename, routingkey:queuename);            var consumer = new Eventingbasicconsumer (channel); Consumer. Received + = (model, ea) = {var msgbody = Encoding.UTF8.GetString (ea).                Body); Console.WriteLine (String.                Format ("* * * Receive time: {0}, message content: {1}", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"), msgbody)); int dots = Msgbody.split ('. ').                Length-1; System.Threading.Thread.Sleep(dots * 1000);                Console.WriteLine ("[x] Done"); When processing is complete, tell broker that the server can delete messages and allocate new messages over the channel. Basicack (Deliverytag:ea.            Deliverytag, Multiple:false);            }; Noack set False, tell the broker, after sending the message, the message is not deleted, and so the consumer processing to complete the channel.            Basicconsume (QueueName, Noack:false, Consumer:consumer);            Console.WriteLine ("Press any value, exit program");        Console.readkey (); }    }}

  

  <2> RABBITMQ Topic Type Exchange

Producter Send Message code:

        <summary>///Connection Configuration///</summary> private static readonly connectionfactory R        Abbitmqfactory = new ConnectionFactory () {HostName = "192.168.1.8", Username= "Hao", password= "abc123", port= 5672        }; <summary>///route name///</summary> const string topexchangename = "Topic.justin.exchan        GE ";        Queue name const string topqueuename = "Topic.justin.queue"; public static void Topicexchangesendmsg () {using (Iconnection conn = Rabbitmqfactory.createconnection () ) {using (IModel CHANNEL = conn. Createmodel ()) {channel.                    Exchangedeclare (topexchangename, "topic", Durable:false, Autodelete:false, arguments:null); Channel.                    Queuedeclare (Topqueuename, Durable:false, Autodelete:false, Exclusive:false, arguments:null); Channel. Queuebind (Topqueuename, topexchangename, routingKey:topqueuename); var props = Channel.                    Createbasicproperties (); Props.                    Persistent = true;                    String vadata = Console.ReadLine ();                        while (Vadata! = "Exit") {var msgbody = Encoding.UTF8.GetBytes (Vadata); Channel.                        Basicpublish (Exchange:topexchangename, Routingkey:topqueuename, Basicproperties:null, body:msgbody); Console.WriteLine (String.                        Format ("* * * Send time: {0}, send complete, enter exit Exit message Send", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"));                    Vadata = Console.ReadLine (); }                }            }        }

Customer receives message code:

        <summary>///Connection Configuration///</summary> private static readonly connectionfactory R Abbitmqfactory = new ConnectionFactory () {HostName = "192.168.1.8", UserName = "Hao", Password = "abc123", Por        t = 5672}; <summary>///route name///</summary> const string topexchangename = "Topic.justin.exchan        GE ";        Queue name const string topqueuename = "Topic.justin.queue";             public static void Topicacceptexchange () {using (Iconnection conn = Rabbitmqfactory.createconnection ()) {using (IModel CHANNEL = conn. Createmodel ()) {channel.                    Exchangedeclare (topexchangename, "topic", Durable:false, Autodelete:false, arguments:null); Channel.                    Queuedeclare (Topqueuename, Durable:false, Autodelete:false, Exclusive:false, arguments:null); Channel. Basicqos (prefetchsize:0, Prefetchcount: 1, Global:false); Channel.                    Queuebind (Topqueuename, Topexchangename, routingkey:topqueuename);                    var consumer = new Eventingbasicconsumer (channel); Consumer. Received + = (model, ea) = {var msgbody = Encoding.UTF8.GetString (ea).                        Body); Console.WriteLine (String.                        Format ("* * * Receive time: {0}, message content: {1}", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"), msgbody)); int dots = Msgbody.split ('. ').                        Length-1;                        System.Threading.Thread.Sleep (dots * 1000);                        Console.WriteLine ("[x] Done"); Channel. Basicack (Deliverytag:ea.                    Deliverytag, Multiple:false);                    }; Channel.                    Basicconsume (Topqueuename, Noack:false, Consumer:consumer);                    Console.WriteLine ("Press any value, exit program");                Console.readkey (); }            }        }

Resources:

Installing the Rabbit MQ Guide on Windows (http://www.cnblogs.com/shanyou/p/4067250.html)

Using RABBITMQ (http://www.cnblogs.com/yangecnu/p/4227535.html) in a. NET environment

RabbitMQ Tutorial (http://www.rabbitmq.com/tutorials/tutorial-six-dotnet.html)

Source code Download

Know the more, do not know the more, learn more!

Rabbitmq.net Applications (1)

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.