RabbitMQ (三)消息重试

本文介绍了RabbitMQ中如何实现消息重试机制,包括手动开启消费者应答和消息重新入列。示例代码展示了消费异常时消息进入死信队列的过程,并探讨了死信队列的配置与使用,以及如何结合Spring Retry和死信队列实现更合理的消息重试策略。此外,还提供了消息生产者、消费者和配置类的完整代码示例。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

1 RabbitMQ自带的重试机制

1 示例代码

rabbitMQ为自带了消息重试机制:当消费者消费消息失败时,可以选择将消息重新“推送”给消费者,直至消息消费成功为止

开启自带的重试机制,需要如下几个配置:

1 开启消费者手动应答机制,对应的springboot配置项:

spring.rabbitmq.listener.simple.acknowledge-mode=manual

2 消费异常时,设置消息重新入列

 boolean multiple = false; // 单条确认
 boolean requeue  = true; // 重新进入队列,谨慎设置!!!很容易导致死循环,cpu 100%
 channel.basicNack(tag, multiple, requeue);

以下是运行例子:

消费者代码如下:

package com.fmi110.rabbitmq;
​
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
​
import java.util.concurrent.atomic.AtomicInteger;
​
/**
 * @author fmi110
 * @description 消息消费者
 * @date 2021/7/1 16:08
 */
@Component
@Slf4j
public class RabbitConsumer {
​
    AtomicInteger count = new AtomicInteger();
​
    @RabbitListener(queues="my-queue")
    public void consumer1(String data, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception{
​
        log.info(">>>> consumer1 消费 tag = {},次数count={},消息内容 : {}",tag, count.incrementAndGet(),data);
     
        try {
            Thread.currentThread().sleep(1000);
            int i = 1/0;
            channel.basicAck(tag,true); // 确认消息消费成功
        } catch (Exception e) {
            log.error(">>>>消费异常,消息重新进入队列并消费");
            boolean multiple = false; // 单条确认
            boolean requeue  = true; // 重新进入队列,谨慎设置!!!
            channel.basicNack(tag, multiple, requeue);
        }
    }
​
    @RabbitListener(queues="my-queue")
    public void consumer2(String data, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception{
        log.info(">>>> consumer2 消费 tag = {},次数count={},消息内容 : {}",tag, count.incrementAndGet(),data);
​
        try {
            Thread.currentThread().sleep(1000);
            int i = 1/0;
            channel.basicAck(tag,true); // 确认消息消费成功
        } catch (Exception e) {
            log.error(">>>>消费异常,消息重新进入队列并消费");
            boolean multiple = false; // 单条确认
            boolean requeue  = true; 
            channel.basicNack(tag, multiple, requeue);
        }
    }
}
​

这里模拟了两个消费者 consumer1consumer2 ,并在逻辑中人为设置异常 int 1/0 , 在异常捕获中通过

 channel.basicNack(tag, false, true);

设置消息重新进入队列,最终推给消费者再次消费。运行结果如下:

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值