What is MassTransit and How to Use It Basically ?

In today’s world of software development, distributed systems and microservices are becoming increasingly prevalent. Developing such applications can introduce a multitude of complexities, which is where MassTransit comes into play as a powerful tool for managing and facilitating communication in distributed applications. MassTransit is a powerful tool for managing distributed systems and microservices. With its core features such as asynchronous communication, scalability, ease of integration, and error handling, it can make complex applications more understandable and maintainable. In this article, we will exploring how to harness the advantages of the MassTransit library. This library can be a significant asset on your journey of developing distributed applications.

What Is MassTransit?

MassTransit is an open-source messaging library designed for the .NET ecosystem. It excels in enabling communication and secure data transfer between applications, especially in the realm of asynchronous, distributed applications. In this article, you will explore how to leverage the MassTransit library to build robust and scalable distributed applications.

Example Scenario Of Using MassTransit

In this scenario, the Order Service receives customer orders and initiates payment processing. If the payment is successful, it sends a message to the Stock Service to decrement the product’s stock. The Stock Service updates the stock levels and informs the Order Service of the outcome. Subsequently, the Order Service sends an order confirmation to the customer, completing the transaction. This scenario illustrates how MassTransit facilitates communication and workflow management among different microservices within a distributed system.

Key Features of MassTransit

MassTransit boasts several crucial features that assist in developing distributed applications:

  1. Asynchronous Messaging: MassTransit is robust in the realm of asynchronous messaging, optimizing communication between components of your application and enhancing performance.
  2. Ease of Integration: The library seamlessly integrates with popular message queuing systems such as RabbitMQ, Azure Service Bus, Amazon SQS, allowing you to start quickly by leveraging existing infrastructure.
  3. Multiple Message Types: It supports various message types (e.g., commands, events, requests), allowing you to establish a communication model that suits your application’s needs.
  4. Scalability: MassTransit is designed to support high-traffic applications, addressing scalability concerns effectively.
  5. Error Handling: It offers features for handling errors during message transmission, including automatic retries.

Let’s Get Started

With MassTransit, you can use the most widely used message brokers such as RabbitMQ, Azure Service Bus, Amazon SQS or you can use it as InMemory in a single application. We will start with an application that works as InMemory to get to know MassTransit and learn its working logic from the basics. First, open a new console application and install the MassTransit library in your project by running the following command

dotnet add package MassTransit

In its simplest form, I created the project as follows. In the “Models” folder, we add the message types to be used in MassTransit messaging as interfaces. Under the “Consumers” folder, we have consumer classes that consume messages from these message types. In Program.cs, there are the codes where the bus settings are made and the operations that send and receive messages are done.

The models are as follows

public interface IOrderSubmitted 
{
  Guid OrderId { get; }
  DateTime Timestamp { get; }
}

public interface IUserCreated 
{
  Guid Id { get; set; }
  string Name { get; set; }
  string Email { get; set; }
}

public class OrderSubmitted : IOrderSubmitted 
{
  public Guid OrderId { get; set; }
  public DateTime Timestamp { get; set; }
}

public class UserCreated : IUserCreated 
{
  public Guid Id { get; set; }
  public string Name { get; set; }
  public string Email { get; set; }
}

Consumers are as follows

public class OrderSubmittedConsumer : IConsumer<IOrderSubmitted>
{
    public async Task Consume(ConsumeContext<IOrderSubmitted> context)
    {
        var order = context.Message;
        Console.WriteLine($"Received order: {order.OrderId} submitted at {order.Timestamp}");
    }
}

public class UserCreatedConsumer : IConsumer<IUserCreated>
{
    public async Task Consume(ConsumeContext<IUserCreated> context)
    {
        var user = context.Message;
        Console.WriteLine($"Created User: {user.Id} # {user.Name} # {user.Email}");
    }
}

Program.cs is as follows

class Program
{
    static void Main(string[] args)
    {
        var busControl = Bus.Factory.CreateUsingInMemory(
            cfg =>
            {
                cfg.ReceiveEndpoint("order_queue", e =>
                    {
                        e.Consumer<OrderSubmittedConsumer>();
                    }
                );
                cfg.ReceiveEndpoint("notify_queue", e =>
                    {
                        e.Consumer<UserCreatedConsumer>();
                    }
                );
            }
        );

        busControl.Start();

        var producer = busControl.GetSendEndpoint(new Uri("loopback://localhost/order_queue")).GetAwaiter().GetResult();

        producer.Send(new OrderSubmitted 
        { 
            OrderId = Guid.NewGuid(), Timestamp = DateTime.Now 
        });
        
        Console.WriteLine("Enter to stop");
        Console.Read();
       
        busControl.Stop();
    }
}

Before explaining the GetSendEndpoint method, it is necessary to explain the “Send” and “Publish” methods used to send messages in MassTransit. “Send” and “Publish” are the two basic message delivery methods used in messaging libraries such as MassTransit or message queuing systems. Both are used to communicate, but they are preferred for different scenarios and requirements.

Send” Method:

The “Send” method is primarily used to send a message directly to a specific recipient. It is typically employed when the goal is to instruct a single recipient or target to perform a specific action. “Send” is suitable for sending a command or making a specific request directly to a target. It is appropriate for scenarios such as initiating a payment transaction or sending a file download request.

Publish” Method:

The “Publish” method is used to broadcast a message to one or more subscribers. It is particularly useful for scenarios where an event is triggered or when multiple recipients need to be informed about a specific topic. “Publish” is employed to disseminate a message to all subscribers associated with a particular topic or event. Consequently, multiple recipients receive this message. “Publish” is suitable for scenarios such as triggering an event, announcing updated data, or notifying multiple parties about the system’s status. It is used whenever multiple recipients need to be notified.

GetSendEndpoint method is a useful method when using MassTransit or a similar messaging library, especially when you want to send messages to dynamic destinations. This method allows you to dynamically specify a destination for sending a message to a specific subject or recipient.

Especially in distributed systems or microservice architectures, you may encounter situations where recipients are not known in advance or may change dynamically. In such cases, instead of sending a message to a fixed recipient, you may want to determine the recipient at runtime. If the destination recipients are not predetermined and change dynamically based on a specific condition or event or if you want to deliver your messages to the recipient based on a specific topic or category, you can use GetSendEndpoint.

If you want to send the message to multiple recipients instead of sending the message to a specific recipient, or if you do not want to deal with the recipient information detail when sending a message, you can send a message with the Publish method.

busControl.Publish(new OrderSubmitted
{
    OrderId = Guid.NewGuid(),
    Timestamp = DateTime.Now
}).Wait();

When you run this application, you will get the following result

Using MassTransit In Asp.Net Core Web Application

To use MassTransit in an Asp.Net Core web application (WebAPI, MVC, RazorPages, Blazor etc), see the example below. Note that this example is also developed with the InMemory method. For RabbitMQ, different settings are required for both MassTransit and the RabbitMQ interface (Queue, Exchange).

The ConfigureServices method in the Startup.cs file should be as follows

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddMassTransit(cfg =>
            {
                cfg.AddConsumer<OrderSubmittedConsumer>();
                cfg.UsingInMemory((ctx, mcfg) =>
                {
                    mcfg.ConfigureEndpoints(ctx);
                });
            });
        }

Since RazorPages is used in this example, you can use an IndexModel like the one below. The IPublishEndpoint interface is automatically injected into the controller by the MassTransit dependency injection library. You can send the data to all recipients using the Publish method in this interface. When you run this web application and when the page opens, you will see that the consumer named OrderSubmittedConsumer is executing.

public class IndexModel : PageModel
{
    private readonly IPublishEndpoint _publishEndpoint;
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger, IPublishEndpoint publishEndpoint)
    {
        _publishEndpoint = publishEndpoint;
        _logger = logger;
    }

    public void OnGet()
    {
        _publishEndpoint.Publish(
            new OrderSubmitted { 
                Id = Guid.NewGuid(), 
                Timestamp = DateTime.Now 
            }
        );
    }
}

MassTransit is a powerful tool for developing and managing distributed systems and microservice architectures. Throughout this article, we’ve explored the key features and usage of MassTransit and explored how this library can be helpful when building distributed applications. As a result, MassTransit stands out as a powerful tool for the development of distributed systems and microservices architectures. This library provides developers with a powerful communication infrastructure and greatly simplifies the development of distributed applications. Using MassTransit, you can build more efficient and scalable distributed applications and lay a strong foundation for your future software projects.

0.0 Ort. (0% puan) - 0 oy

Bir cevap yazın

E-posta hesabınız yayımlanmayacak.