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.






Masstransit



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: github.com/masstransit/masstransit






RabbitMQ



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: http://www.rabbitmq.com



Download and install: http://www.rabbitmq.com/download.html






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:


Using MassTransit;
Using MassTransit.RabbitMqTransport;
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading.Tasks;

Namespace Lezhima.Comm
{
    /// <summary>
    /// RabbitMQ public action class, based on the MassTransit library
    /// </summary>
    Public class RabbitMQHelp
    {
        #region exchanger

        /// <summary>
        /// Operation log exchanger
        /// At the same time, you need to create the same name switch in the management background of RabbitMQ.
        /// </summary>
        Public static readonly string actionLogExchange = "Lezhima.ActionLogExchange";


        #endregion


        #region Declare variables

        /// <summary>
        /// MQ connection address, it is recommended to put in the configuration file
        /// </summary>
        Private static readonly string mqUrl = "rabbitmq://192.168.1.181/";

        /// <summary>
        /// MQ connection account, it is recommended to put in the configuration file
        /// </summary>
        Private static readonly string mqUser = "admin";

        /// <summary>
        /// MQ connection password, it is recommended to put in the configuration file
        /// </summary>
        Private static readonly string mqPwd = "admin";

        #endregion

        /// <summary>
        /// Create a connection object
        /// Not open to the public
        /// </summary>
        Private static IBusControl CreateBus(Action<IRabbitMqBusFactoryConfigurator, IRabbitMqHost> registrationAction = null)
        {
            / / Create MQ connection factory through MassTransit
            Return Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                Var host = cfg.Host(new Uri(mqUrl), hst =>
                {
                    hst.Username(mqUser);
                    hst.Password(mqPwd);
                });
                registrationAction?.Invoke(cfg, host);
            });
        }


        /// <summary>
        /// MQ producer
        /// Use the fanout exchange type here
        /// </summary>
        /// <param name="obj"></param>
        Public async static Task PushMessage(string exchange, object obj)
        {
            Var bus = CreateBus();
            Var sendToUri = new Uri($"{mqUrl}{exchange}");
            Var endPoint = await bus.GetSendEndpoint(sendToUri);
            Await endPoint.Send(obj);
        }

        /// <summary>
        /// MQ consumer
        /// Use the fanout exchange type here
        /// consumer must be an instance of a class that implements the IConsumer interface
        /// </summary>
        /// <param name="obj"></param>
        Public static void ReceiveMessage(string exchange, object consumer)
        {
            Var bus = CreateBus((cfg, host) =>
            {
                / / Get messages from the specified message queue Through the consumer to achieve message reception
                cfg.ReceiveEndpoint(host, exchange, e =>
                {
                    e.Instance(consumer);
                });
            });
            bus.Start();
        }
    }
} 





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:


Using MassTransit;
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading.Tasks;

Namespace Lezhima.Storage.Consumer
{
     /// <summary>
     /// Receive and process data from MQ
     /// Implement the Iconsumer interface of MassTransit
     /// </summary>
     Public class LogConsumer : IConsumer<ActionLog>
     {
         /// <summary>
         /// Implement the Consume method
         /// Receive and process data
         /// </summary>
         /// <param name="context"></param>
         /// <returns></returns>
         Public Task Consume(ConsumeContext<ActionLog> context)
         {
             Return Task.Run(async () =>
             {
                 / / Get the received object
                 Var amsg = context.Message;
                 Console.WriteLine($"Recevied By Consumer:{amsg}");
                 Console.WriteLine($"Recevied By Consumer:{amsg.ActionLogId}");
             });
         }
     }
} 





Calling code



1. The producer call code is as follows:


/// <summary>
/// Test MQ producers
/// </summary>
/// <returns></returns>
[HttpGet]
Public async Task<MobiResult> AddMessageTest()
{
     / / Declare an entity object
     Var model = new ActionLog();
     model.ActionLogId = Guid.NewGuid();
     model.CreateTime = DateTime.Now;
     model.UpdateTime = DateTime.Now;
     / / Call MQ
     Await RabbitMQHelp.PushMessage(RabbitMQHelp.actionLogExchange, model);

     Return new MobiResult(1000, "Operation succeeded");
} 





2, the consumer call code is as follows:


Using Lezhima.Storage.Consumer;
Using Microsoft.Extensions.Configuration;
Using System;
Using System.IO;

Namespace Lezhima.Storage
{
     Class Program
     {
         Static void Main(string[] args)
         {
             Var conf = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", true, true)
               .Build();

             / / call the receiver
             RabbitMQHelp.ReceiveMessage(RabbitMQHelp.actionLogExchange,
              New LogConsumer()
             );

             Console.ReadLine();
         }
     }
} 





Summarize



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.






Statement



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

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.