如果队列消息字节长度大于 x-max-length-bytes,RabbitMQ 如何处理?

How RabbitMQ handle if queue message bytes length large than x-max-length-bytes?

我声明了一个如下所示的队列:

Map<String, Object> args = new HashMap<String, Object>();
args.put("x-max-length-bytes", 2 * 1024 * 1024);  // Max length is 2G
channel.queueDeclare("queueName", true, false, false, args);

当队列消息计数字节大于2G时,会自动移除队列头部的消息。
但我期望的是,它拒绝生成最后一条消息,并向生产者发出 return 异常。
我怎样才能得到它?

如官方文档所述:

Messages will be dropped or dead-lettered from the front of the queue to make room for new messages once the limit is reached.

https://www.rabbitmq.com/maxlength.html

如果您认为 RabbitMQ 应该丢弃队列末尾的消息,请随时在这里提出问题,以便我们讨论 https://github.com/rabbitmq/rabbitmq-server/issues

一种可能的解决方法是在使用 HTTP API.

发送邮件之前检查队列大小

例如,如果您有一个名为的队列:myqueuetest,最大大小 = 20。

在发送消息之前,您可以这样调用 HTTP API: http://localhost:15672/api/queues/

结果是 JSON 这样的:

  "message_bytes":10,
  "message_bytes_ready":10,
  "message_bytes_unacknowledged":0,
  "message_bytes_ram":10,
  "message_bytes_persistent":0,
..
  "name":"myqueuetest",
  "vhost":"test",
  "durable":true,
  "auto_delete":false,
  "arguments":{
     "x-max-length-bytes":20
  },

然后您在发送消息之前云读取 message_bytes 字段,然后决定是否发送。

希望对您有所帮助

编辑

  1. 此解决方法可能会降低您的应用程序性能
  2. 如果您有 multi-threading/more 发布者
  3. ,则此解决方法不安全
  4. 这个解决方法不是很好 "best practise"

试试看它是否适合您的应用程序。