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

相关推荐
三十..2 小时前
Ceph分布式存储核心技术精要与运维实践指南
运维·分布式·ceph
cfm_29146 小时前
Redis高并发分布式锁了解
redis·分布式
小小编程路7 小时前
分布式核心知识
分布式
bukeyiwanshui7 小时前
20260528 Ceph 分布式存储 集群配置
分布式·ceph
Vick_Zhang8 小时前
ubuntu上rabbitmq
服务器·ubuntu·rabbitmq
我叫张小白。8 小时前
基于Redis与FastAPI的分布式共享会话体系
数据库·redis·分布式·缓存·中间件·fastapi·依赖注入
天河归来8 小时前
国产数据库安全可靠测评产品观察:从集中式、分布式到 HTAP 的发展趋势
数据库·分布式
小碗羊肉9 小时前
【Redis | 第五篇】分布式锁
数据库·redis·分布式
运维栈记9 小时前
Ceph 入门:一文读懂分布式存储的“瑞士军刀”
分布式·ceph
头歌实践平台9 小时前
HBase 完全分布式安装(新)
数据库·分布式·hbase