1.none
配置文件
spring:
rabbitmq:
listener:
simple:
acknowledge-mode: none # 关闭ack
none:只要消息到达消费者,即使消费者宕机了,Spring依然直接返回ack到MQ,确认签收;MQ收到ack,会把队列中的消息删除,消息会丢失
2.手动ack
配置文件
spring:
rabbitmq:
listener:
simple:
acknowledge-mode: manual # 手动ack
@RabbitListener(bindings = @QueueBinding( value = @Queue(name = "direct.queue1"), exchange = @Exchange(name = "itcast.direct",type = ExchangeTypes.DIRECT), key = {"blue","red"} )) public void directQueue1(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)Long tag) { log.info("direct.queue1收到的消息:{}",message); try { Thread.sleep(2000); //发生异常 int i = 1/0; //手动ack channel.basicAck(tag,false); } catch (Exception e) { //e.printStackTrace(); try { //手动ack,让消息重回队列,参数三表示是否重回队列 channel.basicNack(tag,false,true); } catch (Exception e1) { e.printStackTrace(); } } }
3.自动ack
配置文件
spring:
rabbitmq:
listener:
simple:
acknowledge-mode: auto# 自动ackretry:
enabled: true #开启消费者失败重试
initial-interval: 2000 #初始的失败等待时长为2秒
multiplier: 2 #失败的等待时长倍数,下次等待时长 = multiplier * last-interval
max-attempts: 3 #最大重试次数
stateless: true #true无状态;false有状态。如果业务中包含事务,这里改为false
当到达重试次数仍然失败:
处理方式一:
RejectAndDontRequeueRecoverer:重试耗尽后,直接reject,丢弃消息。默认就是这种方式
处理方式二:
ImmediateRequeueMessageRecoverer:重试耗尽后,返回nack,消息重新入队
处理方式三:
RepublishMessageRecoverer:重试耗尽后,将失败消息投递到指定的交换机
处理方式三的使用:
//消费者端,声明error交换机、队列和路由key
@Configuration public class RabbitConfig { @Bean public Queue errorQueue(){ return new Queue("error.queue"); } @Bean public DirectExchange errorDirect(){ return new DirectExchange("error.direct"); } @Bean public Binding errorQueueDirect(Queue errorQueue,DirectExchange errorDirect){ return BindingBuilder.bind(errorQueue).to(errorDirect).with("error"); } @Bean //失败策略:重试次数耗尽后,会把消息投递到错误的队列,由错误队列去消费 public MessageRecoverer publishMessageRecoverer(RabbitTemplate rabbitTemplate){ return new RepublishMessageRecoverer(rabbitTemplate,"error.direct","error"); } }
//监听
@RabbitListener(bindings = @QueueBinding( value = @Queue(name = "direct.queue1"), exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT), key = {"blue", "red"} )) public void directQueue1(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) Long tag) throws InterruptedException { log.info("direct.queue1收到的消息:{}", message); int i = 1 / 0; } @RabbitListener(queues = "error.queue") public void directErrorQueue(String messsage) { log.info("error.queue收到的消息" + messsage); //记录日志,后面人工干预,向运维人员不断法短信发邮件 }