基于springboot实现的rabbitmq消息确认

深碍√TFBOYSˉ_ 2023-10-15 23:50 99阅读 0赞

目录

    • 概述
    • 步骤
      • 1、引入rabbitmq包
      • 2、yml配置文件
      • 3、消息转换器MessageConverterConfig
      • 4、消息发送确认
      • 5、配置类(定义exchange和queue,并将queue绑定在exchange)
      • 6、消息发送者
      • 7、消息消费者
      • 8、测试方法
      • 9、补充

概述

RabbitMQ的消息确认有两种。 一种是消息发送确认。这种是用来确认生产者将消息发送给交换器,交换器传递给队列的过程中,消息是否成功投递。发送确认分为两步,一是确认是否到达交换器,二是确认是否到达队列。 第二种是消费接收确认。这种是确认消费者是否成功消费了队列中的消息。

步骤

1、引入rabbitmq包

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-amqp</artifactId>
  4. </dependency>

2、yml配置文件

  1. spring:
  2. rabbitmq:
  3. #连接地址
  4. host: 192.168.56.10
  5. #端口号
  6. port: 5672
  7. #账号
  8. username: guest
  9. #密码
  10. password: guest
  11. #虚拟主机
  12. virtual-host: /
  13. #开启发送端消息抵达broker的确认
  14. publisher-confirm-type: correlated
  15. #开启发送端消息抵达队列的确认
  16. publisher-returns: true
  17. template:
  18. #mandatory 默认为FALSE,指定消息在没有被队列接收时是否强行退回还是直接丢弃,如果exchange根据自身类型和消息routeKey无法找到一个符合条件的queue,会直接将消息扔掉
  19. mandatory: true
  20. listener:
  21. simple:
  22. # 设置消费端手动 ack
  23. acknowledge-mode: manual

3、消息转换器MessageConverterConfig

  1. package com.itheima.config;
  2. import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
  3. import org.springframework.amqp.support.converter.MessageConverter;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. /**
  7. * @author: XuXin
  8. * @date: 2023/9/26
  9. */
  10. @Configuration
  11. public class MessageConverterConfig {
  12. /**
  13. * 使用json序列化机制,进行消息转换
  14. */
  15. @Bean
  16. public MessageConverter messageConverter() {
  17. return new Jackson2JsonMessageConverter();
  18. }
  19. }

4、消息发送确认

发送消息确认:用来确认生产者 producer 将消息发送到 broker ,broker 上的交换机 exchange 再投递给队列 queue的过程中,消息是否成功投递。
消息从 producer 到 rabbitmq broker有一个 confirmCallback 确认模式。
消息从 exchange 到 queue 投递失败有一个 returnCallback 退回模式。
我们可以利用这两个Callback来确保消息的100%送达。

  1. ConfirmCallback确认模式
    消息只要被 rabbitmq broker 接收到就会触发 confirmCallback 回调 。

    package com.itheima.producer;

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.amqp.rabbit.connection.CorrelationData;
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.stereotype.Component;

    /**

    • @author: XuXin
    • @date: 2023/9/22
      */
      @Slf4j
      @Component
      public class ConfirmCallback implements RabbitTemplate.ConfirmCallback {

      /**

      • 不管消息是否成功到达交换机都会被调用
        *
      • @param correlationData 当前消息的唯一关联数据(这个是消息的唯一id)
      • @param ack 消息是否成功收到 只要消息抵达broker就ack=true
      • @param cause 失败的原因
        */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        log.info(“ 回调id:” + correlationData);
        if (ack) {

        1. log.info("消息成功发送");

        } else {

        1. log.info("消息发送失败:" + cause);

        }
        }
        }

实现接口 ConfirmCallback ,重写其confirm()方法,方法内有三个参数correlationData、ack、cause。
correlationData:对象内部只有一个 id 属性,用来表示当前消息的唯一性。
ack:消息投递到broker 的状态,true表示成功。
cause:表示投递失败的原因。
但消息被 broker 接收到只能表示已经到达 MQ服务器,并不能保证消息一定会被投递到目标 queue 里。所以接下来需要用到 returnCallback。

  1. ReturnCallback 退回模式
    如果消息未能投递到目标 queue 里将触发回调 returnCallback ,一旦向 queue 投递消息未成功,这里一般会记录下当前消息的详细投递数据,方便后续做重发或者补偿等操作。

    package com.itheima.producer;

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.amqp.core.ReturnedMessage;
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.stereotype.Component;

    /**

    • @author: XuXin
    • @date: 2023/9/25
      */
      @Slf4j
      @Component
      public class ReturnCallback implements RabbitTemplate.ReturnsCallback {

      /**

      • @param re 只有在交换机到达队列失败的时候才会被触发,当这个回调函数被调用的时候说明交换机的消息没有顺利的到达队列
      • message 投递失败的消息详细信息
      • replyCode 回复的状态码
      • replyText回复的文本内容
      • exchange 当时这个消息发给哪个交换机
      • routingKey 当时这个消息发给哪个路由键
        */
        @Override
        public void returnedMessage(ReturnedMessage re) {

        log.info(“Returned: “ + re.getMessage() + “\nreplyCode: “ + re.getReplyCode()

        • “\nreplyText: “ + re.getReplyText() + “\nexchange: “
        • re.getExchange() + “\nroutingKey: “ + re.getRoutingKey());
          }
          }

实现接口ReturnCallback,重写 returnedMessage() 方法,方法有五个参数message(消息体)、replyCode(响应code)、replyText(响应内容)、exchange(交换机)、routingKey(队列)。
在rabbitTemplate中设置 Confirm 和 Return 回调,我们通过setDeliveryMode()对消息做持久化处理,为了后续测试创建一个 CorrelationData对象,添加一个id 为10000000000。

5、配置类(定义exchange和queue,并将queue绑定在exchange)

  1. package com.itheima.config;
  2. import com.itheima.producer.ConfirmCallback;
  3. import com.itheima.producer.ReturnCallback;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.amqp.core.*;
  6. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.beans.factory.annotation.Qualifier;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import javax.annotation.PostConstruct;
  12. /**
  13. * @author xx
  14. * @date 2023/9/22
  15. * springboot自动读取yml文件自动配置,这里可删
  16. * 定义完成后 rabbitmq服务器会自动创建交换机和队列以及绑定关系
  17. * 在Spring启动时,利用Spring Bean管理工厂BeanFactory接口,实现动态创建交换机、队列、交换机和队列的绑定关系,让我们无需进行重复的编码工作。
  18. */
  19. @Slf4j
  20. @Configuration
  21. public class RabbitMQConfig {
  22. @Autowired
  23. private RabbitTemplate rabbitTemplate;
  24. @Autowired
  25. private ConfirmCallback confirmCallback;
  26. @Autowired
  27. private ReturnCallback returnCallback;
  28. /**
  29. * 队列
  30. */
  31. public static final String QUEUE1 = "atguigu";
  32. public static final String QUEUE2 = "atguigu.news";
  33. public static final String QUEUE3 = "atguigu.emps";
  34. public static final String QUEUE4 = "gulixueyuan.news";
  35. /**
  36. * 定义交换机名称
  37. */
  38. public static final String EXCHANGE_DIRECT_NAME = "exchange.direct";
  39. public static final String EXCHANGE_FANOUT_NAME = "exchange.fanout";
  40. public static final String EXCHANGE_TOPIC_NAME = "exchange.topic";
  41. /**
  42. * 设置路由key
  43. * #匹配0个或多个单词,*匹配一个单词
  44. */
  45. public static final String ROUTINGKEY1 = "atguigu";
  46. public static final String ROUTINGKEY2 = "atguigu.news";
  47. public static final String ROUTINGKEY3 = "atguigu.emps";
  48. public static final String ROUTINGKEY4 = "gulixueyuan.news";
  49. public static final String ROUTINGKEY5 = "atguigu.#";
  50. public static final String ROUTINGKEY6 = "*.news";
  51. /**
  52. * 定义 直连交换机
  53. */
  54. @Bean("directExchange")
  55. public DirectExchange directExchange() {
  56. //参数 交换机名称
  57. return new DirectExchange(EXCHANGE_DIRECT_NAME, true, false);
  58. }
  59. /**
  60. * 定义 扇形交换机
  61. */
  62. @Bean("fanoutExchange")
  63. public FanoutExchange fanoutExchange() {
  64. //参数 交换机名称
  65. return new FanoutExchange(EXCHANGE_FANOUT_NAME, true, false);
  66. }
  67. /**
  68. * 定义 主题交换机
  69. */
  70. @Bean("topicExchange")
  71. public TopicExchange topicExchange() {
  72. //参数 交换机名称
  73. return new TopicExchange(EXCHANGE_TOPIC_NAME, true, false);
  74. }
  75. /**
  76. * 创建队列
  77. * 参数一:队列名称
  78. * 参数二durable:是否持久化,默认是false,持久化队列:会被存储在磁盘上,当消息代理重启时仍然存在,暂存队列:当前连接有效
  79. * 参数三exclusive:默认也是false,是否独占队列
  80. * 参数四autoDelete:是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除。
  81. */
  82. @Bean("queue1")
  83. public Queue queue1() {
  84. return new Queue(QUEUE1, true, false, false);
  85. }
  86. @Bean("queue2")
  87. public Queue queue2() {
  88. return new Queue(QUEUE2, true, false, false);
  89. }
  90. @Bean("queue3")
  91. public Queue queue3() {
  92. return new Queue(QUEUE3, true, false, false);
  93. }
  94. @Bean("queue4")
  95. public Queue queue4() {
  96. return new Queue(QUEUE4, true, false, false);
  97. }
  98. /**
  99. * 队列绑定交换机
  100. *
  101. * @param queue 队列注入到容器的id,也就是方法名 Queue1
  102. * @param directExchange 交换机注入到容器的id,也就是方法名 directExchange
  103. * @return
  104. */
  105. @Bean
  106. public Binding bindingQueue1DirectExchange(@Qualifier("queue1") Queue queue, @Qualifier("directExchange") DirectExchange directExchange) {
  107. return BindingBuilder.bind(queue).to(directExchange).with(ROUTINGKEY1);
  108. }
  109. @Bean
  110. public Binding bindingQueue2DirectExchange(@Qualifier("queue2") Queue queue, @Qualifier("directExchange") DirectExchange directExchange) {
  111. return BindingBuilder.bind(queue).to(directExchange).with(ROUTINGKEY2);
  112. }
  113. @Bean
  114. public Binding bindingQueue3DirectExchange(@Qualifier("queue3") Queue queue, @Qualifier("directExchange") DirectExchange directExchange) {
  115. return BindingBuilder.bind(queue).to(directExchange).with(ROUTINGKEY3);
  116. }
  117. @Bean
  118. public Binding bindingQueue4DirectExchange(@Qualifier("queue4") Queue queue, @Qualifier("directExchange") DirectExchange directExchange) {
  119. return BindingBuilder.bind(queue).to(directExchange).with(ROUTINGKEY4);
  120. }
  121. @Bean
  122. public Binding bindingQueue1FanoutExchange(@Qualifier("queue1") Queue queue, @Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
  123. return BindingBuilder.bind(queue).to(fanoutExchange);
  124. }
  125. @Bean
  126. public Binding bindingQueue2FanoutExchange(@Qualifier("queue2") Queue queue, @Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
  127. return BindingBuilder.bind(queue).to(fanoutExchange);
  128. }
  129. @Bean
  130. public Binding bindingQueue3FanoutExchange(@Qualifier("queue3") Queue queue, @Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
  131. return BindingBuilder.bind(queue).to(fanoutExchange);
  132. }
  133. @Bean
  134. public Binding bindingQueue4FanoutExchange(@Qualifier("queue4") Queue queue, @Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
  135. return BindingBuilder.bind(queue).to(fanoutExchange);
  136. }
  137. @Bean
  138. public Binding bindingQueue1TopicExchange(@Qualifier("queue1") Queue queue, @Qualifier("topicExchange") TopicExchange topicExchange) {
  139. return BindingBuilder.bind(queue).to(topicExchange).with(ROUTINGKEY5);
  140. }
  141. @Bean
  142. public Binding bindingQueue2TopicExchange(@Qualifier("queue2") Queue queue, @Qualifier("topicExchange") TopicExchange topicExchange) {
  143. return BindingBuilder.bind(queue).to(topicExchange).with(ROUTINGKEY5);
  144. }
  145. @Bean
  146. public Binding bindingQueue3TopicExchange(@Qualifier("queue3") Queue queue, @Qualifier("topicExchange") TopicExchange topicExchange) {
  147. return BindingBuilder.bind(queue).to(topicExchange).with(ROUTINGKEY5);
  148. }
  149. @Bean
  150. public Binding bindingQueue4TopicExchange(@Qualifier("queue4") Queue queue, @Qualifier("topicExchange") TopicExchange topicExchange) {
  151. return BindingBuilder.bind(queue).to(topicExchange).with(ROUTINGKEY6);
  152. }
  153. /**
  154. * 定制rabbitTemplate
  155. * 1、服务收到消息就回调
  156. * 1、spring.rabbitmq.publisher-confirms=true
  157. * 2、设置确认回调ConfirmCallback
  158. * 2、消息正确抵达队列进行回调
  159. * 1、spring.rabbitmq.publisher-returns=true
  160. * spring.rabbitmq.template.mandatory= true
  161. * 2、设置确认回调ReturnCallback
  162. * <p>
  163. * 3、消费端确认(保证每个消息被正确消费,此时才可以broker删除这个消息)。
  164. * listener.simple.acknowledge-mode=manual
  165. * 1、默认是自动确认的,只要消息接收到,客户端会自动确认,服务端就会移除这个消息
  166. * 问题:
  167. * 我们收到很多消息,自动回复给服务器ack,只有一个消息处理成功,宕机了。发生消息丢失;
  168. * 消费者手动确认。只要我们没有明确告诉MQ,货物被签收。没有Ack,消息就一 直是unacked状态。即使Consumer宕机,
  169. * 消息也不会丢失,会重新变为Ready,下次有新的Consumer连接进来就发给他
  170. * 2、如何签收:
  171. * channel.basicAck(deliveryTag, false) ;签收;业务成功完成就应该签收
  172. * channel.basicNack(deliveryTag, false, true);拒签;业务失败,拒签|
  173. */
  174. @PostConstruct
  175. public void initRabbitTemplate() {
  176. //设置确认回调
  177. rabbitTemplate.setConfirmCallback(confirmCallback);
  178. rabbitTemplate.setReturnsCallback(returnCallback);
  179. }
  180. }

6、消息发送者

  1. package com.itheima.producer;
  2. import com.itheima.config.RabbitConfig;
  3. import org.springframework.amqp.rabbit.connection.CorrelationData;
  4. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Component;
  7. import java.util.UUID;
  8. /**
  9. * @author: XuXin
  10. * @date: 2023/9/25
  11. * 1、发送消息,如果发送的消息是个对象,我们会使用序列化机制,将对象写出去。对象必须实现Serializable
  12. */
  13. @Component
  14. public class MsgProducer {
  15. @Autowired
  16. private RabbitTemplate rabbitTemplate;
  17. public void sendMsg(String routingKey, Object content) {
  18. CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
  19. //把消息放入ROUTINGKEY_A对应的队列当中去,对应的是队列A
  20. rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_DIRECT_NAME, routingKey, content, correlationId);
  21. }
  22. public void sendMsg(String routingKey, Object content, String uuid) {
  23. CorrelationData correlationId = new CorrelationData(uuid);
  24. //把消息放入ROUTINGKEY_A对应的队列当中去,对应的是队列A
  25. rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_DIRECT_NAME, routingKey, content, correlationId);
  26. }
  27. }

7、消息消费者

  1. package com.itheima.receiver;
  2. import com.itheima.domain.Book;
  3. import com.rabbitmq.client.Channel;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.rabbit.annotation.RabbitHandler;
  7. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  8. import org.springframework.stereotype.Component;
  9. import java.io.IOException;
  10. /**
  11. * @author: XuXin
  12. * @date: 2023/9/25
  13. */
  14. @Slf4j
  15. @Component
  16. @RabbitListener(queues = "atguigu.news")
  17. public class MsgReceiver {
  18. /**
  19. * queues: 声明需要监听的所有队列
  20. * org.springframework-amqp.core.Message
  21. * 参数可以写一下类型
  22. * 1、Message message: 原生消息详细信息。头+体
  23. * 2、T<发送的消息的类型> OrderReturnReasonEntity content;
  24. * 3、Channel channel: 当前传输数据的通道
  25. * <p>
  26. * Queue: 可以很多人都来监听。只要收到消息,队列删除消息,而且只能有一个收到此消息
  27. * 场景:
  28. * 1)、订单服务启动多个;同一个消息,只能有一个客户端收到
  29. * 2)、只有一个消息完全处理完,方法运行结束,我们就可以接收到下一-个消息
  30. *
  31. * @param message
  32. * @param content
  33. * @throws IOException
  34. */
  35. @RabbitHandler
  36. public void processHandler(Message message, Book content, Channel channel) throws IOException {
  37. try {
  38. log.info("收到消息:{}", content);
  39. //TODO 具体业务
  40. //是deliveryTagchannel内按顺序自增的
  41. long deliveryTag = message.getMessageProperties().getDeliveryTag();
  42. //签收消息,非批量模式
  43. channel.basicAck(deliveryTag, false);
  44. } catch (Exception e) {
  45. log.error("消息即将再次返回队列处理...");
  46. //退货 requeue=false丢弃 requeue=true发回服务器,服务器重新入队。
  47. //long deliveryTag, boolean multiple, boolean requeue
  48. channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
  49. }
  50. }
  51. }

监听消息必须要有@EnableRabbit注解,如果只是创建交换机,队列以及绑定不需要此注解。
消费消息有三种回执方法,我们来分析一下每种方法的含义。
1、basicAck

  • basicAck:表示成功确认,使用此回执方法后,消息会被rabbitmq broker 删除。
    void basicAck(long deliveryTag, boolean multiple)
  • deliveryTag:表示消息投递序号,每次消费消息或者消息重新投递后,deliveryTag都会增加。手动消息确认模式下,我们可以对指定deliveryTag的消息进行ack、nack、reject等操作。
  • multiple:是否批量确认,值为 true 则会一次性 ack所有小于当前消息 deliveryTag 的消息。
    举个栗子: 假设我先发送三条消息deliveryTag分别是5、6、7,可它们都没有被确认,当我发第四条消息此时deliveryTag为8,multiple设置为 true,会将5、6、7、8的消息全部进行确认。

2、basicNack

  • basicNack :表示失败确认,一般在消费消息业务异常时用到此方法,可以将消息重新投递入队列。
    void basicNack(long deliveryTag, boolean multiple, boolean requeue)
  • deliveryTag:表示消息投递序号。
    multiple:是否批量确认。
  • requeue:值为 true 消息将重新入队列。

3、basicReject

  • basicReject:拒绝消息,与basicNack区别在于不能进行批量操作,其他用法很相似。
    void basicReject(long deliveryTag, boolean requeue)
  • deliveryTag:表示消息投递序号。
  • requeue:值为 true 消息将重新入队列。

8、测试方法

  1. package com.itheima.controller;
  2. import com.itheima.config.RabbitConfig;
  3. import com.itheima.domain.Book;
  4. import com.itheima.producer.MsgProducer;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. /**
  10. * @author: XuXin
  11. * @date: 2023/9/25
  12. */
  13. @Slf4j
  14. @RestController
  15. public class TestRabbitMq {
  16. @Autowired
  17. private MsgProducer msgProducer;
  18. @GetMapping("/sendMq")
  19. public String sendMq() {
  20. System.out.println("执行");
  21. Book book = new Book();
  22. book.setName("cook");
  23. book.setType("eat");
  24. msgProducer.sendMsg(RabbitConfig.ROUTINGKEY2,book);
  25. return "ok";
  26. }
  27. }

9、补充

  1. 别忘确认消息
    这是一个非常没技术含量的坑,但却是非常容易犯错的地方。
    开启消息确认机制,消费消息别忘了channel.basicAck,否则消息会一直存在,导致重复消费。
  2. 消息无限投递
    在我最开始接触消息确认机制的时候,消费端代码就像下边这样写的,思路很简单:处理完业务逻辑后确认消息, int a = 1 / 0 发生异常后将消息重新投入队列。

    @RabbitHandler

    1. public void processHandler(String msg, Channel channel, Message message) throws IOException {
    2. try {
    3. log.info("消费者 2 号收到:{}", msg);
    4. int a = 1 / 0;
    5. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    6. } catch (Exception e) {
    7. channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
    8. }
    9. }
  3. 重复消费
    如何保证 MQ 的消费是幂等性,这个需要根据具体业务而定,可以借助MySQL、或者redis将消息持久化,通过再消息中的唯一性属性校验。
    可以看到使用了 RabbitMQ 以后,我们的业务链路明显变长了,虽然做到了系统间的解耦,但可能造成消息丢失的场景也增加了。例如:
    消息生产者 - > rabbitmq服务器(消息发送失败)
    rabbitmq服务器自身故障导致消息丢失
    消息消费者 - > rabbitmq服务(消费消息失败)

发表评论

表情:
评论列表 (有 0 条评论,99人围观)

还没有评论,来说两句吧...

相关阅读

    相关 RabbitMQ消息确认模式

    一 概述 生产者发送消息后,这个消息的确认对于MQ来说,MQ会拥有自己的确认模式来完成。 二 RabbitMQ的消息确认模式 当我们发送消息后,服务端如何知道消息

    相关 rabbitmq消息确认机制

    rabbitmq消费确认机制分三种:生产者消息确认机制、消费者消息确认机制、return消息机制 一、生产者消息确认机制 生产者消息确认机制:指生产者将消息投递给对应的