RabbitMQ Learning Series (iii): How C # uses RabbitMQ

Source: Internet
Author: User
Tags rabbitmq

The previous article has talked about RABBITMQ how to install the Windows platform, and do not know how to install friends, please see my previous articles: RABBITMQ Learning Series One: Under Windows installation RABBITMQ Services, today to talk about the real development of C # in the process, how to call With RABBITMQ.


 First, the client 

RabbitMQ has a lot of client APIs that are very useful. We are on the side, has been using EASYNETQ, so the demo here only describes the EASYNETQ client implementation. Other clients, let's study it by ourselves.

EASYNETQ is an easy-to-use RABBITMQ. NET Client API.   Address: http://easynetq.com/. Demo sample Download.


  II. Structure of the project

    

Description: As we mentioned earlier, RABBITMQ consists of Producer (generator) and Consumer (consumer). Weiz.consumer is Consumer (consumer), Weiz. Producer is Producer (generator), WEIZ.MQ is a generic processing class library for Message Queuing.


  Iii. Construction of the project

    1. WEIZ.MQ Project , a generic processing class library for Message Queuing, is used for both subscribed and published messages.

1. EASYNETQ related components via NuGet installation project (slightly)

2. Add BusBuilder.cs pipeline creation class, mainly responsible for linking RABBITMQ.

usingSystem;usingSystem.Configuration;usingeasynetq;namespaceweiz.mq{/// <summary>    ///Message Server Connector/// </summary>     Public classBusbuilder { Public StaticIBus Createmessagebus () {//Message Server connection string//var connectionString = configurationmanager.connectionstrings["RabbitMQ"];            stringConnString ="host=192.168.98.107:5672;virtualhost=orderqueue;username=zhangweizhong;password=weizhong1988"; if(connstring = =NULL|| ConnString = =string. Empty) {Throw NewException ("messageserver connection string is missing or empty"); }                        returnRabbithutch.createbus (connstring); }    }}
View Code

3. Add Iprocessmessage class, define a message method for message passing

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace weiz.mq{    publicinterface  iprocessmessage    {        void  processmsg (Message msg);}    }
View Code

4. Add a message class that defines information such as entity attribute fields for messaging

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceweiz.mq{ Public classMessage { Public stringMessageID {Get;Set; }  Public stringMessageTitle {Get;Set; }  Public stringMessageBody {Get;Set; }  Public stringMessagerouter {Get;Set; } }}
View Code

5. Add the Mqhelper class for the subscribing and publishing messages that are in progress.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Configuration;usingeasynetq;namespaceweiz.mq{ Public classMqhelper {/// <summary>        ///Send Message/// </summary>         Public Static voidPublish (Message msg) {////Create message busIBus bus =Busbuilder.createmessagebus (); Try{bus. Publish (msg, x=x.withtopic (Msg.            Messagerouter)); }            Catch(Easynetqexception ex) {//handling Connection Message Server exceptions} bus. Dispose ();//similar to database connection, remember to destroy bus objects after use        }        /// <summary>        ///Receiving Messages/// </summary>        /// <param name= "msg" ></param>         Public Static voidSubscribe (Message msg, iprocessmessage ipro) {////Create message busIBus bus =Busbuilder.createmessagebus (); Try{bus. Subscribe<Message> (Msg. Messagerouter, message = ipro. PROCESSMSG (message), x =x.withtopic (Msg.            Messagerouter)); }            Catch(Easynetqexception ex) {//handling Connection Message Server exceptions            }        }    }}
View Code

2. Rabbitmq by Producer (creator)

1. Create an ASPX page and add the following code

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingweiz.mq;namespaceweiz.producer{ Public Partial classTestMQ:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e) {        }        protected voidButton1_Click (Objectsender, EventArgs e) {Message msg=NewMessage (); Msg. MessageID="1"; Msg. MessageBody=DateTime.Now.ToString (); Msg. MessageTitle="1"; Msg. Messagerouter="Pcm.notice.zhangsan";        Mqhelper.publish (msg); }    }}
View Code

    3. Weiz.consumer is Consumer (consumer)

1. New OrderProcessMessage.cs

using System; using System.Collections.Generic; using System.Linq; using system.web; namespace weiz.consumer{    publicclass  orderprocessmessage:mq. Iprocessmessage    {        publicvoid  processmsg (MQ. Message msg)        {            Console.WriteLine (msg. MessageBody);     }}}
View Code

2. Program add the following code

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceweiz.consumer{classProgram {Static voidMain (string[] args) {Orderprocessmessage Order=NewOrderprocessmessage (); Mq. Message msg=NewMQ.            Message (); Msg. MessageID="1"; Msg. Messagerouter="Pcm.notice.zhangsan"; Mq.        Mqhelper.subscribe (msg, order); }    }}
View Code

Four, the operation

1. Start Weiz.consumer (consumer), start the consumer, and automatically create the relevant exchange and queue on the RABBITMQ server.

      

Consumer the consumer, using the Subscribe (subscription) mode, the Weiz.consumer client starts, automatically creates connection, and generates the relevant exchange and queue.

2. Start Weiz. Producer the testmq.aspx page, write a message to the queue. Subscribers are immediately able to get the message.

       

 

At this point, C # sends a message to the RABBITMQ message queue that has been simply completed.

View RABBITMQ Series other articles, http://www.cnblogs.com/zhangweizhong/category/855479.html

RabbitMQ Learning Series (iii): How C # uses RabbitMQ

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.