DLX: Dead Letter Exchange
利用DLX,当消息在一个队列中变成死信(dead message:消息在该队列中没有消费者去消费)之后,它就会被重新publish到另一个Exchange中,这个Exchange就是DLX;死信队列和普通队列并没有区别,只是相关属性进行了设置;
消息变成死信的几种情况
- 消息被拒绝:basic.reject/basic.nack,且requeue=false;
- 消息TTL:消息过期;
- 队列达到最大长度:例如队列的最大长度是3000,第3001条消息就是死信,该死信会被转发到死信队列;
死信队列的设置
- Exchange:dlx.exhcange
- Queue: dlx.queue
- RoutingKey: #
- Arguments: arguments.put(“x-dead-letter-exchange”, “dlx.exchange”)
代码例子
Producer.java
public class Producer {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("xxx.xxx.xxx.xxx");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
String exchange = "test_dlx_exchange";
String routingKey = "dlx.save";
String msg = "Hello RabbitMQ DLX Message";
for(int i =0; i<1; i ++){
AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
.deliveryMode(2)
.contentEncoding("UTF-8")
.expiration("10000")
.build();
channel.basicPublish(exchange, routingKey, true, properties, msg.getBytes());
}
}
}
Consumer.java
public class Consumer {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("xxx.xxx.xxx.xxx");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
// 这就是一个普通的交换机 和 队列 以及路由
String exchangeName = "test_dlx_exchange";
String routingKey = "dlx.#";
String queueName = "test_dlx_queue";
channel.exchangeDeclare(exchangeName, "topic", true, false, null);
Map<String, Object> agruments = new HashMap<String, Object>();
agruments.put("x-dead-letter-exchange", "dlx.exchange");
//这个agruments属性,要设置到声明队列上
channel.queueDeclare(queueName, true, false, false, agruments);
channel.queueBind(queueName, exchangeName, routingKey);
//要进行死信队列的声明:
channel.exchangeDeclare("dlx.exchange", "topic", true, false, null);
channel.queueDeclare("dlx.queue", true, false, false, null);
channel.queueBind("dlx.queue", "dlx.exchange", "#");
channel.basicConsume(queueName, true, new MyConsumer(channel));
}
}