Reputation: 163
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;
}
Upvotes: 0
Views: 168
Reputation: 1526
RabbitMQ is meesage queue which is based on publisher and consumer. So
"channel.BasicAck" is used to send acknowledgement.
API methods used for delivery acknowledgement are usually exposed as operations on a channel in client libraries. Java client users will use Channel#basicAck and Channel#basicNack to perform a basic.ack and basic.nack, respectively. MoreDetail
If Not use Basicack then Messages will be redelivered when your client quits (which may look like random redelivery), but RabbitMQ will eat more and more memory as it won't be able to release any unacked messages. More Details
"_channel.BasicConsume" is used to recieve message as consumer and do needful operation on queue as consumer.
For more detail, Please refer the above links.
Upvotes: 1