.Net Core&RabbitMQ限制循环消费( 四 )


.Net Core&RabbitMQ限制循环消费

文章插图
设定消费者端第五十条消息会被拒收,且队列的TTL设置为5秒 。
//死信交换机和死信队列var dlxExchangeName = "dlx_exchange";channel.ExchangeDeclare(exchange: dlxExchangeName, type: "fanout", durable: false, autoDelete: false, arguments: null);var dlxQueueName = "dlx_queue";channel.QueueDeclare(queue: dlxQueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);channel.QueueBind(queue: dlxQueueName, exchange: dlxExchangeName, routingKey: "");//常规队列var queueName = "normalmessage_queue";var arguments = new Dictionary<string, object>{    { "x-message-ttl", 5000},    { "x-dead-letter-exchange", dlxExchangeName }};channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: arguments);channel.BasicQos(0, 5, false);var consumer = new EventingBasicConsumer(channel);consumer.Received += (model, ea) =>{    var message = ea.Body;    Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message.ToArray()));    if (Encoding.UTF8.GetString(message.ToArray()).Contains("50"))    {        Console.WriteLine($"拒收 {DateTime.Now}");        ((EventingBasicConsumer)model).Model.BasicReject(ea.DeliveryTag, requeue: true);        return;    }    ((EventingBasicConsumer)model).Model.BasicAck(ea.DeliveryTag, multiple: false);};channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);当消费者端拒收消息后消息重入队列,再次消费,反复进行超过5秒后 , 消息在队列中达到了过期时间,则被挪入到死信队列中 。
.Net Core&amp;RabbitMQ限制循环消费

文章插图
从Web管理中死信队列中可查看该条过期的消息 。
.Net Core&amp;RabbitMQ限制循环消费

文章插图
参考资料
  1. https://www.jianshu.com/p/f77a0b10c140
  2. https://www.jianshu.com/p/4904c609632f
  3. https://stackoverflow.com/questions/23158310/how-do-i-set-a-number-of-retry-attempts-in-rabbitmq
2022-10-29,望技术有成后能回来看见自己的脚步

推荐阅读