The usage of Basic.RabbitMQ is quite simple.
- Install
Basic.RabbitMQ
NuGet package from here.
PM> Install-Package Basic.RabbitMQ
- Add services.AddRabbitMQClient(Configuration);
builder.Services.AddRabbitMqClient(Configuration);
- Add the necessary information to the
appsettings.json
file.
"MessageBrokerOptions": {
"HostName": "",
"UserName": "",
"Password": "",
"ExchangeName": "",
"VirtualHost": "",
"Port": -1
}
- And start using it. And that's it.
Producer
[ApiController]
public class ProducerController(IMessageProducer messageProducer) : ControllerBase
{
[HttpPost("/sendMessage")]
public Task<IActionResult> SendMessage(string message)
{
messageProducer.SendMessage("Test_Queue", "Test_Routing_Key", message);
return Task.FromResult<IActionResult>(Ok());
}
}
Consumer
var messageConsumer = serviceProvider.GetService<IMessageConsumer>();
var channel = messageConsumer?.Channel("Test_Queue", "Test_Routing_Key");
var basicConsumer = messageConsumer?.GetConsumer(channel);
basicConsumer!.Received += BasicConsumerReceived;
Task BasicConsumerReceived(object sender, BasicDeliverEventArgs @event)
{
var message = Encoding.UTF8.GetString(@event.Body.ToArray());
Console.WriteLine($" [>] Received {message}");
channel?.BasicAck(@event.DeliveryTag, false);
await Task.Yield();
}