RabbitMQ:死信隊列DLX介紹及演示

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));
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章