简体   繁体   中英

C# - RabbitMQ - Doubts about RabbitMQ Methods

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;
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM