ASP. NET Core 2.0 leverages Masstransit integrated RABBITMQ

Source: Internet
Author: User
Tags message queue rabbitmq

Using Masstransit to integrate with RABBITMQ on the ASP. is really easy, and the code is simple. Recently, as a result of the project, I have once again encapsulated the public method, making the invocation of RABBITMQ easier and simpler. So let's take a look at the charm.


Let's see what Masstransit is, Baby (Masstransit's profile):

Masstransit is a free, open source lightweight message bus for use. NET Framework to create distributed applications. Masstransit provides a wide range of features on existing top-level message transmissions to use the message-based session-mode asynchronous connection service in a developer-friendly manner. Message-based communication is a reliable and extensible way to implement a service-oriented architecture.

Popular Description:

Masstransit is a high-level package library based on message service, which can join RABBITMQ, Redis, MongoDB and other services downstream.

GitHub website:


RABBITMQ is a mature MQ queuing service that is an open source implementation of AMQP developed by the Erlang language. About the introduction of RABBITMQ's Chinese information is also many, there is a need to find their own. I posted a link to download and install the website here, as follows:

Official website:

Download and install:

Implementation code

With the introduction above, we have a preliminary understanding of masstransit and RABBITMQ, so let's look at how to use the RABBITMQ gracefully on the ASP.

1. Create a public class called "RabbitMQHelp.cs", which encapsulates the public method of Operation RabbitMQ, and manages and references the "Masstransit" and "MASSTRANSIT.RABBITMQ" class libraries through NuGet.

2, "RabbitMQHelp.cs" public class mainly external package two static methods, the code is as follows:

1 usingMasstransit;2 usingMasstransit.rabbitmqtransport;3 usingSystem;4 usingSystem.Collections.Generic;5 usingSystem.Text;6 usingSystem.Threading.Tasks;7 8 namespaceLezhima.comm9{Ten     // <summary> One     // RABBITMQ Public operation class, based on Masstransit library A     // </summary> -      Public classRabbitmqhelp -{ the#region Exchanger -  -         // <summary> -         /// operation log Exchanger +         ///At the same time create a switch with the same name in RABBITMQ admin background -         // </summary> +          Public Static ReadOnly stringActionlogexchange = "Lezhima.actionlogexchange"; A  at  -#endregion -  -  -#region declaring variables -  in         // <summary> -         /// MQ-join address, recommended for configuration file to         // </summary> +         Private Static ReadOnly stringMqurl = "rabbitmq://"; -  the         // <summary> *         /// MQ Connection account, recommended to be placed in configuration file $         // </summary>Panax Notoginseng         Private Static ReadOnly stringMquser = "Admin"; -  the         // <summary> +         /// MQ join password, recommended to be placed in configuration file A         // </summary> the         Private Static ReadOnly stringMqpwd = "Admin"; +  -#endregion $  $         // <summary> -         /// Create Connection object -         // not open to external the         // </summary> -         Private StaticIbuscontrol Createbus (action<irabbitmqbusfactoryconfigurator, irabbitmqhost> registrationAction =NULL)Wuyi{ the             //Create an MQ join factory via Masstransit -             returnBus.Factory.CreateUsingRabbitMq (cfg = Wu{ -var host = cfg. Host (NewUri (mqurl), HST = About{ $Hst. Username (Mquser); -Hst. Password (MQPWD); -}); -Registrationaction?. Invoke (CFG, host); A}); +} the  -  $         // <summary> the         // MQ producer the         /// Use the Fanout exchange type here the         // </summary> the         /// <param name= "obj" ></param> -          PublicAsyncStaticTask Pushmessage (stringExchangeObjectObj in{ thevar bus = Createbus (); thevar Sendtouri =NewUri ($ "{Mqurl}{exchange}"); Aboutvar endPoint = await bus. Getsendendpoint (Sendtouri); theAwait endpoint.send (obj); the} the  +         // <summary> -         // MQ consumer the         /// Use the Fanout exchange type hereBayi         /// consumer must be a class instance that implements the Iconsumer interface the         // </summary> the         /// <param name= "obj" ></param> -          Public Static voidReceiveMessage (stringExchangeObjectConsumer -{ thevar bus = Createbus (cfg, host) = = the{ the                 //Get messages from the specified message queue for message reception via consumer theCfg. Receiveendpoint (host, exchange, E = -{ theE.instance (consumer); the}); the});94Bus. Start (); the} the} the}98 

3, "RabbitMQHelp.cs" public class already has MQ "producer" and "consumer" two external static public methods, wherein the "producer" method can be called directly in the business code, can pass JSON, object and other types of parameters to send data to the specified exchanger. The "consumer" method is to receive the binding from the specified exchanger, but the received data processing function is given to the "Consumer" class (because in the actual project, different data has different business processing logic, so here we directly through the Iconsumer interface to the specific implementation class to do). So, let's take a look at the code of the "Consumer" class that the consumer is passing in:

1 usingMasstransit;2 usingSystem;3 usingSystem.Collections.Generic;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 7 namespaceLezhima.Storage.Consumer8{9     // <summary>Ten     /// receive and process data from MQ One     /// implementation of Masstransit Iconsumer interface A     // </summary> -      Public classLogconsumer:iconsumer<actionlog> -{ the         // <summary> -         /// implement consume method -         /// Receive and process data -         // </summary> +         /// <param name= "context" ></param> -         // <returns></returns> +          PublicTask consume (consumecontext<actionlog> context) A{ at    (Async () = -{ -                 //Get the Received object -var amsg = context. Message; -Console.WriteLine ($ "recevied by consumer:{amsg}"); -Console.WriteLine ($ "recevied by Consumer:{amsg. Actionlogid}"); in}); -} to} +} - 

Calling code

1. The producer call code is as follows:

1 // <summary>2 /// test MQ producer3 // </summary>4 // <returns></returns>5[HttpGet]6  PublicAsync task<mobiresult> Addmessagetest ()7{8     //Declare an entity object9var model =NewActionlog ();TenModel. Actionlogid = Guid.NewGuid (); OneModel. Createtime = DateTime.Now; AModel. UpdateTime = DateTime.Now; -     //Call MQ -Await Rabbitmqhelp.pushmessage (rabbitmqhelp.actionlogexchange, model); the  -     return NewMobiresult (1000, "Operation succeeded"); -}

2, the consumer call code is as follows:

1 usingLezhima.Storage.Consumer;2 usingMicrosoft.Extensions.Configuration;3 usingSystem;4 usingSystem.IO;5 6 namespaceLezhima.storage7{8     classProgram9{Ten         Static voidMain (string[] args) One{ Avar conf =NewConfigurationbuilder () -. Setbasepath (Directory.GetCurrentDirectory ()) -. Addjsonfile ("Appsettings.json",true,true) the. Build (); -  -             //Call recipient -Rabbitmqhelp.receivemessage (Rabbitmqhelp.actionlogexchange, +              NewLogconsumer () -); +  AConsole.ReadLine (); at} -} -} - 


1, based on the Masstransit library makes us use RABBITMQ become more concise and convenient. And based on the re-encapsulation, producers and consumers will not need to focus on specific business, but also with the business code decoupling, more adaptable to the needs of the project.

2, RABBITMQ the switch needs to be created in its own management background, and the type of fanout used here is because of its fastest sending, and can meet my project needs, you may choose different types of their own situation. The fanout type does not store the message, and the consumer must bind the switch before it is sent to the consumer.


This article is the author original, please note the source and retain the original address, thank you. If the article can bring you help, please click on the recommendation or attention, thank you for your support!

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.