Chd.Library.MQ 9.0.5

There is a newer version of this package available.
See the version list below for details.
dotnet add package Chd.Library.MQ --version 9.0.5                
NuGet\Install-Package Chd.Library.MQ -Version 9.0.5                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Chd.Library.MQ" Version="9.0.5" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Chd.Library.MQ --version 9.0.5                
#r "nuget: Chd.Library.MQ, 9.0.5"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Chd.Library.MQ as a Cake Addin
#addin nuget:?package=Chd.Library.MQ&version=9.0.5

// Install Chd.Library.MQ as a Cake Tool
#tool nuget:?package=Chd.Library.MQ&version=9.0.5                

RabbitMQ library for .Net Core

Chd (cleverly handle difficulty) library helps you cleverly handle difficulty, writing code fastly and do your application stable.

๐Ÿ“ Table of Contents

๐Ÿง About

A message queue is a form of asynchronous service-to-service communication used in serverless and microservices architectures. Messages are stored on the queue until they are processed and deleted. Each message is processed only once, by a single consumer. Message queues can be used to decouple heavyweight processing, to buffer or batch work, and to smooth spiky workloads.

๐Ÿ Getting Started

RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP). This middleware is a popular, reliable, and scalable platform for building realtime applications.

Prerequisites

You must use .net core 9.0 or higher

๐ŸŽˆ Usage

We will create a container for the message queue. We will produce messages to the queue and consume them. We will use the RabitMQ for this purpose.

โœ๏ธ Writing Sample Classs For Message

We will create a SampleClass and EmailMessage class for producing messages. We will create instance the SampleClass and set SerializableObject property to EmailMessage intance. We will produce the SampleClass instance to the queue. We will consume the SampleClass instance and get the EmailMessage instance from the SerializableObject property.

public class SampleClass
{
    public object SerializableObject { get; set; }
    public string Message { get; set; }
    public string Description { get; set; }
}

public class EmailMessage : 
{
    public string To { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
}

๐Ÿ’‰ Injection RabitMQ and It's Message Producer Into The Project

We will inject the RabitMQ and it's message producer into the project. We will use the AddMQ and AddMQProducer methods for this purpose. We will use the AddMQ method for injecting the RabitMQ into the project. If we needs message producing, we should use the Add MQProducer method for injecting the message producer.

var builder = WebApplication.CreateBuilder(args);
......
......
builder.Services.AddMQ();
builder.Services.AddMQProducer<SampleClass>();

๐Ÿš€ Producing Some Messages To RabitMQ

We will create a controller for producing messages to the RabitMQ. We will use the Producer class for producing messages. We will use the SendMessage method for producing messages. We will set the first parameter of the SendMessage method to the SampleClass instance. We will set the second parameter of the SendMessage method to the boolean value. We will set the third parameter of the SendMessage method to the queue name. The other parameters are optional. We do not need to enter them. We may set the fourth parameter of the SendMessage method to the exchange name. We may set the fifth parameter of the SendMessage method to the routing key.

public class RabbitMQTestController : Controller
{
    public Producer<SampleClass> Producer { get; }

    public RabbitMQTestController(Producer<SampleClass> producer)
    {
        Producer = producer;
    }

    [Route("AddMessagesToRabbitMQ")]
    [HttpGet]
    public string? AddMessagesToRabbitMQ()//For testing on swagger or etc..
    {
        var emailMessage = new EmailMessage { To="to",Content="test rabbitMQ",Subject="test"};
        Producer.SendMessage(new SampleClass { SerializableObject = emailMessage, Description = "Test1",Message= "xxx" },true,queueName:"testQueue");
        return "Ok";
    }

}

๐ŸŽŠ Consume Messages From RabitMQ

We will create a consumer service for consuming messages from the RabitMQ. We will create a class that inherits the ConsumerServiceBase class. We will override the OnMessageDelivered method for consuming messages. We will override the OnErrorOccured method for handling errors.


public class SampleConsumerService : ConsumerBase<SampleClass>
{
    public SampleConsumerService(ConnectionFactory connectionFactory) : base(connectionFactory)
    {

    }
    protected override string QueueName => "testQueue";

    public override Task ReceiveAction(SampleClass message)
    {
        //Write your code here
        return Task.CompletedTask;
    }
}

we will add hosted service for consuming messages from the RabitMQ. We will use the AddHostedService method for adding the hosted service. We will use the AddSingleton method for injecting the SampleConsumerService class into the project.

For using this CronJobService, you must add the Chd.Library.Service package to your project. You can search the Chd.Library.Service package on the Nuget Package Manager and install it.

We set the CronJob attribute to the RabbitMqSamapleService. We set the value of the CronJob attribute to the cron expression. We override the Run method for consuming messages. We override the StartAsync method for starting the consumer service. We create an instance of the SampleConsumerService class in the StartAsync method. We call the Connect method of the SampleConsumerService class in the Run method.

```bash
```csharp
    [CronJob("*/1 * * * *")]
    public class RabbitMqSamapleService : CronJobService
    {
        public ConnectionFactory ConnectionFactory { get; }
        public RabbitMqSamapleService(ConnectionFactory connectionFactory)
        {
            ConnectionFactory = connectionFactory;
        }
        public override void Run(CancellationToken cancellationToken)
        {
           if(sampleConsumerService.Status==false)
            {
                sampleConsumerService.Connect();
            }
           
        }
        SampleConsumerService sampleConsumerService;
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            sampleConsumerService = new SampleConsumerService(ConnectionFactory);
            sampleConsumerService.Connect();
            return base.StartAsync(cancellationToken);
        }

    }

โš™๏ธ Apsettings Configurations

You must add code below in appsettings.json

  "MQ": {
    "Host": "localhost", //change it if you use different host
    "UserName": "YOUR_USERNAME", //change it if you use different username
    "Password": "YOUR_PASSWORD", //change it if you use different password
    "Port": "5672"    //change it if you use different port
  }

๐Ÿงช Testing The Code For Producing and Consuming Messages

We will run the application. We will call the AddMessagesToRabbitMQ method of the RabbitMQTestController class. We may use swagger or postman for calling the AddMessagesToRabbitMQ method. We will check the produced messages.

If our message is produced successfully, we will consume the message. Add break points to the ReceiveAction method of the SampleConsumerService class for checking the consumed messages. We will check the consumed messages.

โœ๏ธ Authors

See also the list of contributors who participated in this project.

๐ŸŽ‰ Acknowledgements

Thank you for using my library.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
9.0.7 79 1/30/2025
9.0.6 72 1/30/2025
9.0.5 38 1/11/2025
9.0.4 106 1/1/2025
8.0.1 426 2/3/2024
7.2.7 687 8/9/2023
1.2.7 835 1/30/2023