当一个队列中的消息满足以下情况之一时,可以成为死信(dead letter):
- 消费者使用basic.reject或basic.nack声明消费失败,并且消息的requeue参数设置为false。
- 消息是一个过期消息,超时无人消费。
- 要投递的队列消息堆积满了,最早的消息可能成为死信
如果该队列配置了dead-letter-exchange属性,指定了一个交换机,则队列中的死信就会投递到这个交换机中。这个交换机被称为死信交换机(Dead Letter Exchange,简称DLX)

TTL
TLL,即Time-To-Live。如果一个队列中的消息TTL结束仍未消费,会变为死信,ttl超时分两种情况:
- 消息所在队列设置了存活时间
- 消息本身设置了存活时间
1.声明死信交换机和队列
1 2 3 4 5 6 7 8
| @RabbitListener(bindings = @QueueBinding( value = @Queue(name = "dl.queue", durable = "true"), exchange = @Exchange(name = "dl.direct"), key = "dl" )) public void listenDeadQueue(String msg){ System.out.println("消费者接收到dl.queue的消息:【" + msg + "】"); }
|
2.基于队列设置存活时间,绑定TTL交换机和队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
@Configuration public class TTLMessageConfig {
@Bean public DirectExchange ttlExchange() { return new DirectExchange("ttl.direct", true, false); }
@Bean public Queue ttlQueue() { return QueueBuilder.durable("ttl.queue") .ttl(1000) .deadLetterExchange("dl.direct") .deadLetterRoutingKey("dl") .build(); }
@Bean public Binding ttlBinding() { return BindingBuilder .bind(ttlQueue()) .to(ttlExchange()) .with("ttl"); } }
|
3.基于消息设置存活时间
1 2 3 4 5
| Message message = MessageBuilder.withBody("今天天气不错".getBytes(StandardCharsets.UTF_8)) .setDeliveryMode(MessageDeliveryMode.PERSISTENT) .setExpiration("5000") .build();
|
4.基于死信交换机的延迟队列
