Ezio's Blog
Posts Categories Tags Music Mood About
Ezio's Blog· Light
☰ Menu
Posts Categories Tags Music Mood About
Expand all Back to top Go to bottom

死信交换机

Author: Ezio Date: August 7, 2022  23:11:26 Category: RabbitMQ

当一个队列中的消息满足以下情况之一时,可以成为死信(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
/**
* TTL消息处理
*/
@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.基于死信交换机的延迟队列

Author: Ezio

Permalink: https://ezioy.cn/2022/08/07/%E6%AD%BB%E4%BF%A1%E4%BA%A4%E6%8D%A2%E6%9C%BA/

License: Copyright (c) 2019 CC-BY-NC-4.0 LICENSE

Slogan: Nothing is true,Everything is permitted

Tag(s): # RabbitMQ
back · home
消息堆积 消息丢失
Ezio © 2019 - 2026 | Powered by Hexo & Chic | 访客数量:   浏览次数: | 渝公网安备50011302222043 | 渝ICP备2023013933号-1