RabbitMQ Integration using C# .Net 8 - Message consumer

RabbitMq producer integration using c# .Net 8 (Worker service)

NuGet Package to install:


NuGet\Install-Package MassTransit -Version 8.1.3

 

MQ Receiver: (Message consumer)

Program.cs


services.AddMassTransit(x =>
{
    x.AddConsumer<Worker>();
    x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
    {
        cfg.Host(new Uri(CommonFunc.GetSettingsBySectionAndKey("MQSettings", "RootURI")), h =>
        {
            h.Username(CommonFunc.GetSettingsBySectionAndKey("MQSettings", "UserName"));
            h.Password(CommonFunc.GetSettingsBySectionAndKey("MQSettings", "Password"));
        });
        cfg.ReceiveEndpoint(CommonFunc.GetQueName("MyQueueName"), ep =>
        {
            ep.PrefetchCount = 1;
            ep.UseMessageRetry(r => r.Interval(2, TimeSpan.FromSeconds(5)));
            ep.ConfigureConsumer<Worker>(provider);
        });
    }));
});

 

Worker Class:

Worker.cs


namespace MyMQreceiver
{
	using MassTransit;
    public class Worker : IConsumer
    {
        private readonly ILogger _logger;
        public Worker(ILogger logger)
        {
            _logger = logger;
        }
        public async Task Consume(ConsumeContext context)
        {
            try
            {
                //// your logic goes here
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occured Unable to process the MQ data");
            }
            _logger.LogInformation("CONSUMER END at: {time}", DateTimeOffset.Now);
        }
    }
}

 

--- All the best --- 

 


Summary:

RabbitMQ Message Queue and its implementation using .NET 8 API as a Message Consumer.