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);
}
}
}
这里模拟了两个消费者 consumer1、consumer2 ,并在逻辑中人为设置异常 int 1/0 , 在异常捕获中通过
channel.basicNack(tag, false, true);
设置消息重新进入队列,最终推给消费者再次消费。运行结果如下:

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

被折叠的 条评论
为什么被折叠?



