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.lambda$main$2(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

相关推荐
不被定义的号1 小时前
docker swarm里搭建Selenium Grid分布式测试集群,测试节点随时在线,无需反复启停,效率增倍
分布式·selenium·docker
processflow流程图1 小时前
分布式kettle调度平台- web版转换,作业编排新功能介绍
分布式·kettle二开·kettle-web·webspoon·kettle增强版·kettle web化·web kettle
点点滴滴的记录1 小时前
场景设计:设计一个分布式限流器,采用令牌桶算法,漏桶算法、滑动窗口算法实现
分布式·算法
陈老师还在写代码2 小时前
SpringBoot单机模式的极限是什么?为什么会引入分布式?
spring boot·分布式·后端
柠檬精不吃柠檬5 小时前
Git 分布式版本控制工具使用教程
分布式·git
匠道5 小时前
分布式id探索
分布式
胡八一6 小时前
kafka查看topic消息是否堆积
分布式·kafka
企鹅侠客6 小时前
kafka topic是什么?partition是什么? broker是什么?
分布式·kafka·linq
刘什么洋啊Zz6 小时前
RocketMQ及和Kafka的区别
分布式·kafka·消息队列·rocketmq