I've implemented a listener service using rabbitMQ. I used a log for show the message body received but i dont know the main purpose for "_channel.BasicAck" and "_channel.BasicConsume" methods and why is in that order.
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Serilog;
using System.Text;
using System.Text.Json;
public class ListenerBackgroundService : BackgroundService
{
private readonly ILogger _logger = Log.Logger.ForContext<ListenerBackgroundService();
private readonly IConfiguration _configuration;
private IConnection connection;
private IModel _channel;
public ListenerBackgroundService(IConfiguration configuration)
{
_configuration = configuration;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.ThrowIfCancellationRequested();
var consumer = new AsyncEventingBasicConsumer(_channel);
consumer.Received += async (bc, ea) =>
{
var message = Encoding.UTF8.GetString(ea.Body.ToArray());
var mensaje = JsonSerializer.Deserialize<IntegrationMessage>(message);
try
{
//Add message parsing and handling logic here
_logger.Information(mensaje.Message);
_channel.BasicAck(ea.DeliveryTag, false);
}
catch (Exception ex)
{
_channel.BasicNack(ea.DeliveryTag, false, false);
}
};
_channel.BasicConsume(queue: "hello", autoAck: false, consumer: consumer);
await Task.CompletedTask;
}