RabbitMQ has became one of the most used message brokers in the world, so this is not a surprise if you come to a situation where you need to publish messages to RabbitMQ with .NET Core. This approach allows you to create asynchronous communication and better scalability depending on your architecture. But before we move ahead, it is important to explain a few things.

As per Wikipedia, “RabbitMQ is an open-source message-broker software that originally implemented the Advanced Message Queuing Protocol and has since been extended with a plug-in architecture to support Streaming Text Oriented Messaging Protocol, MQ Telemetry Transport, and other protocols”. It works mostly as a middleware for message handling.

RabbitMQ Logo - Publish messages to RabbitMQ with .NET Core
RabbitMQ Logo

The post will explore the features published and maintained in the RabbitMQ Client library. This library can be found in GitHub. The client, of course, is integrated or imported using NuGet via Visual Studio or NuGet CLI.

Creating the connection to RabbitMQ with .NET Core

The first step is to create a method for creating your Connections. This method will accept a class or any other type of parameters which you can define:

  • Username: the username that will connect to RMQ Broker;
  • Password: the password that will connect to RMQ Broker;
  • Virtual Host: the VHost name of your RMQ where you will be referencing the queue;
  • Hostname: the real hostname of your RMQ implementation;
  • Queue: the name of the queue inside your RMQ instance;
  • Port: the RMQ port for posting messages;
  • Scheme: default will be amqps for SSL connections or amqp for non-SSL;
    • if you come to use SSL connections, pay attention to the certificate you need to reference too.

Publishing messages to RabbitMQ

Now that you have prepared the connection parameters, it is time to publish the messages (drop them to the queue). The code below will guide you on how to do that. Please, assume this is part of a bigger class where you have the cmdInstruction variable initialized.

The first and only parameter messages is a list of strings where you will pass XMLs or JSONs and they will be published to the MQ. The line 16 also uses the property Queue which will define which queue you will be posting to.

Conclusion

Basically that is all for publishing messages. You can definitely take advantage of the library provided by RabbitMQ developers and the community to allow you to publish messages to RabbitMQ with .NET Core. Also you might find useful checking other posts related to RabbitMQ here.

References:
GitHub RabbitMQ Client