Introduction to MassTransit: Messaging with RabbitMQ

Mert Aktaş
Logiwa Tech
Published in
6 min readMar 24, 2022

--

Before we talk about MassTransit and its benefits, we should go over some basic concepts.

What is Message Broker?

A message broker is a software that enables applications, systems, and services to communicate with each other and exchange information. The message broker does this by translating messages between formal messaging protocols. This allows interdependent services to “talk” with one another directly, even if they were written in different languages or implemented on different platforms³.

Message brokers are structures that work with 3 components.

  • Producer: The component where the messages are produced.
  • Queue: The queue structure where the messages are kept.
  • Consumer: The component that processes the messages coming into the queue. It receives messages in the queue and executes transactions.
Example for Message Broker

What is RabbitMQ?

RabbitMQ is the most widely used open source message broker. It works with the message broker basics described above². For detailed information and installation about rabbitmq, you can refer to this link.

What is MassTransit?

MassTransit is a free, open-source distributed application framework for .NET. MassTransit makes it easy to create applications and services that leverage message-based, loosely-coupled asynchronous communication for higher availability, reliability, and scalability.¹

MassTransit works with several message transports and provides an extensive set of developer-friendly features to build durable asynchronous services.

Below you can see the advantages of massTransit.

  • MassTransit supports Azure Service Bus, ActiveMQ, and Amazon SQS/SNS message queues along with Rabbitmq.
  • Many microservice message patterns can be implemented (retry, circuit breaker)
  • Exception Handling is already included.
  • Distributed transaction (event driven state machines, Saga)
  • Monitoring
  • You can test it easily

Now that we have learned the basic structure, we can move on to our example.

I want to talk about our sample application. First of all, I will create a .net core web API project named OrderAPI. This API will insert the incoming order to the sql server and at the same time send this order to my other .net core web API project named NotificationAPI with rabbitmq. On the other hand, NotificationAPI, will send an e-mail with the incoming order information and a response will be returned to the OrderAPI. Finally, I will create a class library called Models that will contain my common models, and a nUnit test project called Test.

Diagram for our example

After creating two .net core web APIs, Nunit test project and class library, our solution looks like below

Let’s code

Models

First let’s start with the Models project. Here we will have the OrderResult and SubmitOrder models that we use in common.

Let’s not forget to add our Models project as a project reference to OrderAPI and NotificationAPI 🙂

Notification API

After that, I switch to notificationAPI which is consumer.

Notification API
Startup.cs

In our startup class, we first added our consumer. Afterwards, we configured that we will use rabbitMQ and which link we will use. Furthermore, we configured which consumer will consume when information is exchanged from the LOrder queue. Finally, configured our MassTransitHostedService, which automatically starts and stops the bus.

Then our OrderConsumer class created.

This class inherits from the IConsumer interface. In this way, we implement the following Consumer function. We do the necessary operations with the incoming context information. Thanks to the RespondAsync function, we return an OrderResult type response. You can see a code block that returns success and sends mail if the OrderId is greater than 0, or returns an error if it is less than 0.

Order API

After that, I switch to OrderAPI which is producer.

Order API
Startup.cs

Unlike what we did in our previous startup class, we only did the requestclient config here. Regarding to that, we can make requests with massTransit and get a response.We also set the request timeout as 10 seconds.

In our endpoint named Post, we first insert the order into the sql server. Then sended order data to the queue and we get an OrderResult type response from OrderConsumer class.

After running our project, we will see a screen similar to the one below.

Since the project is running smoothly, we can send a request and test the project.

Example Request

We send our request with the example body above. After sending our request, our order was first inserted into the sql server.

Sql Server

Then sent to our NotificationAPI project and our notificationAPI project sent the mail about this order.

Notification Api Message
Mail

Finally our notificationAPI project returned us a successful response.

Response

Nunit Test Project

Before we end our article, let’s write our unit tests 🙂.We had already created our test project. After naming our unit test class and filling it in, it will look like below.

As you can see below, we have defined an object of type InMemoryTestHarness named ‘harness’. InMemoryTestHarness replaces your Message Broker for the unit test instance, just like a Mock construct. So, as a broker it has all the messages posted, but it also keeps track of all the messages forwarded.

Then, we made a consumer definition for our harness for the unit test example. After starting our Message Broker, we sent a sample order to the queue.

Thanks to InMemoryTestHarness, we can track all the transmitted messages as I mentioned before. As you can see in the code above, I can check if there is any SubmitOrder in the ‘Consumed’ list. In this way, we can complete the tests whether the endpoint consumes the messages and whether the consumer consumes them. In the finally code block, we stop our Message Broker and we have finished our test.

Conclusion

MassTransit stands before us as a good framework. I believe it is a framework not to be missed with its easy management, dependency injection support, fast - easy coding and easy unit testing support.

You can find the codes of the project here. Please feel free to reach me 🙂Thank you for reading till the end. I hope it was useful.

[1]: Chris Patterson. (March 22 2022). Getting Started
https://masstransit-project.com/

[2]: RabbitMQ Team. Hello World Example
https://www.rabbitmq.com/getstarted.html

[3]: IBM Cloud Education. (January 23 2020). What are Message Brokers?
https://www.ibm.com/cloud/learn/message-brokers

--

--