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:

  1 using MassTransit;
 2 using MassTransit.RabbitMqTransport;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7
 8 namespace Lezhima.Comm
 9 {
 10 /// <summary>
 11 /// RabbitMQ public operation class, based on MassTransit library
 12 /// </summary>
 13 public class RabbitMQHelp
 14 {
 15 #region exchanger
 16
 17 /// <summary>
 18 /// Operation log exchanger
 19 /// At the same time, you need to create the same name switch in the management background of RabbitMQ.
 20 /// </summary>
 21 public static readonly string actionLogExchange = "Lezhima.ActionLogExchange";
 twenty two 
 twenty three 
 24 #endregion
 25
 26
 27 #region declaration variable
 28
 29 /// <summary>
 30 /// MQ connection address, it is recommended to put in the configuration file
 31 /// </summary>
 32 private static readonly string mqUrl = "rabbitmq://192.168.1.181/";
 33
 34 /// <summary>
 35 /// MQ connection account, it is recommended to put in the configuration file
 36 /// </summary>
 37 private static readonly string mqUser = "admin";
 38
 39 /// <summary>
 40 /// MQ connection password, it is recommended to put in the configuration file
 41 /// </summary>
 42 private static readonly string mqPwd = "admin";
 43
 44 #endregion
 45
 46 /// <summary>
 47 /// Create a connection object
 48 /// Not open to the public
 49 /// </summary>
 50 private static IBusControl CreateBus(Action<IRabbitMqBusFactoryConfigurator, IRabbitMqHost> registrationAction = null)
 51 {
 52 //Create MQ connection factory through MassTransit
 53 return Bus.Factory.CreateUsingRabbitMq(cfg =>
 54 {
 55 var host = cfg.Host(new Uri(mqUrl), hst =>
 56 {
 57 hst.Username(mqUser);
 58 hst.Password(mqPwd);
 59 });
 60 registrationAction?.Invoke(cfg, host);
 61 });
 62 }
 63
 64
 65 /// <summary>
 66 /// MQ producer
 67 /// here uses the fanout exchange type
 68 /// </summary>
 69 /// <param name="obj"></param>
 70 public async static Task PushMessage(string exchange, object obj)
 71 {
 72 var bus = CreateBus();
 73 var sendToUri = new Uri($"{mqUrl}{exchange}");
 74 var endPoint = await bus.GetSendEndpoint(sendToUri);
 75 await endPoint.Send(obj);
 76 }
 77
 78 /// <summary>
 79 /// MQ consumers
 80 /// Use the fanout exchange type here
 81 /// consumer must be a class instance that implements the IConsumer interface
 82 /// </summary>
 83 /// <param name="obj"></param>
 84 public static void ReceiveMessage(string exchange, object consumer)
 85 {
 86 var bus = CreateBus((cfg, host) =>
 87 {
 88 //Get the message from the specified message queue. Receive the message through the consumer.
 89 cfg.ReceiveEndpoint(host, exchange, e =>
 90 {
 91 e.Instance(consumer);
 92 });
 93 });
 94 bus.Start();
 95 }
 96 }
 97 }
 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 using MassTransit;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6
 7 namespace Lezhima.Storage.Consumer
 8 {
 9 /// <summary>
 10 /// Receive and process data from MQ
 11 /// Implementing the Iconsumer interface of MassTransit
 12 /// </summary>
 13 public class LogConsumer : IConsumer<ActionLog>
 14 {
 15 /// <summary>
 16 /// Implement the Consume method
 17 /// Receive and process data
 18 /// </summary>
 19 /// <param name="context"></param>
 20 /// <returns></returns>
 21 public Task Consume(ConsumeContext<ActionLog> context)
 twenty two         {
 23 return Task.Run(async () =>
 twenty four             {
 25 //Get the received object
 26 var amsg = context.Message;
 27 Console.WriteLine($"Recevied By Consumer:{amsg}");
 28 Console.WriteLine($"Recevied By Consumer:{amsg.ActionLogId}");
 29 });
 30 }
 31 }
 32 }
 33

Calling code

1. The producer call code is as follows:

   1 /// <summary>
  2 /// Test MQ producer
  3 /// </summary>
  4 /// <returns></returns>
  5 [HttpGet]
  6 public async Task<MobiResult> AddMessageTest()
  7 {
  8 //Declare an entity object
  9 var model = new ActionLog();
  10 model.ActionLogId = Guid.NewGuid();
  11 model.CreateTime = DateTime.Now;
  12 model.UpdateTime = DateTime.Now;
  13 //Invoke MQ
  14 await RabbitMQHelp.PushMessage(RabbitMQHelp.actionLogExchange, model);
  15
  16 return new MobiResult(1000, "Operation succeeded");
  17 }

2, the consumer call code is as follows:

   1 using Lezhima.Storage.Consumer;
  2 using Microsoft.Extensions.Configuration;
  3 using System;
  4 using System.IO;
  5
  6 namespace Lezhima.Storage
  7 {
  8 class Program
  9     {
  10 static void Main(string[] args)
  11 {
  12 var conf = new ConfigurationBuilder()
  13 .SetBasePath(Directory.GetCurrentDirectory())
  14 .AddJsonFile("appsettings.json", true, true)
  15 .Build();
  16
  17 //call the receiver
  18 RabbitMQHelp.ReceiveMessage(RabbitMQHelp.actionLogExchange,
  19 new LogConsumer()
  20);
  twenty one 
  22 Console.ReadLine();
  twenty three         }
  twenty four     }
  25 }
  26

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.

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.