RabbitMQ 消息顺序性保证

方式一:Consumer设置exclusive

注意条件

  • 作用于basic.consume

  • 不支持quorum queue

    当同时有A、B两个消费者调用basic.consume方法消费,并将exclusive设置为true时,第二个消费者会抛出异常:

    com.rabbitmq.client.AlreadyClosedException: channel is already closed due to channel error; protocol method: #method<channel.close>(reply-code=403, reply-text=ACCESS_REFUSED - queue 'test' in vhost '/' in exclusive use, class-id=60, method-id=20)
    at com.rabbitmq.client.impl.AMQChannel.ensureIsOpen(AMQChannel.java:190)
    at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:223)
    at com.rabbitmq.client.impl.ChannelN.basicConsume(ChannelN.java:981)
    at com.dms.rabbitmq.TopicSender.lambdamain2(TopicSender.java:63)
    at java.base/java.lang.Thread.run(Thread.java:840)

Spring AMQP 如何通过exclusive实现顺序消费:


核心逻辑

复制代码
while (!DirectMessageListenerContainer.this.started && isRunning()) {
   this.cancellationLock.reset();
   try {
      for (String queue : queueNames) {
         consumeFromQueue(queue);
      }
   }
   catch (AmqpConnectException | AmqpIOException e) {
      long nextBackOff = backOffExecution.nextBackOff();
      if (nextBackOff < 0 || e.getCause() instanceof AmqpApplicationContextClosedException) {
         DirectMessageListenerContainer.this.aborted = true;
         shutdown();
         this.logger.error("Failed to start container - fatal error or backOffs exhausted",
               e);
         this.taskScheduler.schedule(this::stop, Instant.now());
         break;
      }
      this.logger.error("Error creating consumer; retrying in " + nextBackOff, e);
      doShutdown();
      try {
         Thread.sleep(nextBackOff); // NOSONAR
      }
      catch (InterruptedException e1) {
         Thread.currentThread().interrupt();
      }
      continue; // initialization failed; try again having rested for backOff-interval
   }
   DirectMessageListenerContainer.this.started = true;
   DirectMessageListenerContainer.this.startedLatch.countDown();
}
  1. 抛出异常后,会重试
  2. 重试间隔、次数受recoveryInterval(默认无限)、recoveryBackOff控制

方式二:single active consumer

原理:

代码示例

复制代码
Channel ch = ...;
Map<String, Object> arguments = newHashMap<String, Object>();
arguments.put("x-single-active-consumer", true);
ch.queueDeclare("my-queue", false, false, false, arguments);

参考资料:https://www.rabbitmq.com/blog/2022/07/05/rabbitmq-3-11-feature-preview-single-active-consumer-for-streams

相关推荐
Thomas.Sir17 小时前
第21课:PyTorch|GPU多卡训练与分布式训练基础【让多卡并行成为你的加速引擎】
人工智能·pytorch·分布式
Cicada12818 小时前
库存消息消费的正确性设计——从幂等窗口到批量流水线
分布式·系统架构
Francek Chen2 天前
【大数据处理与分析】数据仓库Hive:04 数据仓库Hive概述
大数据·数据仓库·hive·hadoop·分布式
Gl�ria2 天前
Hadoop/YARN 集群缩容:下线DN节点
大数据·hadoop·分布式
吉甫作诵2 天前
Kafka 集群安装与运维实战:消费组排查、Offset 重置与副本重分配
大数据·运维·分布式·kafka·消息队列
imDwAaY2 天前
消息队列四大核心问题:顺序性、幂等性、可靠性与一致性
学习·kafka·rabbitmq
是Dream呀3 天前
Harness 工程:让 Agent 真正把任务做完
人工智能·分布式·缓存·agent
yt004yt3 天前
绿岛数字化平台搭建:VOCs 监测与能碳数据一体化方案
大数据·分布式
天天喝旺仔3 天前
分布式服务容错实战:用 Sentinel 实现限流、熔断与降级
分布式·微服务·云原生·sentinel