原文来源于:程序员恰恰
如有侵权,联系删除
定义:
死信,顾名思义就是死亡的消息,一般来说, 消息生产者 将消息投递到 broker 或者直接到 queue 里了, 消息消费者 从 queue 取出消息进行消费,但某些时候由于特定的原因导致 queue 中的某些消息无法被消费,就变成了死信,存放有死信的队列就是死信队列。
死信的来源:
-
消息 TTL 过期
-
队列达到最大长度(队列满了,无法再添加数据到 mq 中)
-
消息被拒绝(basic.reject 或 basic.nack)并且 requeue=false.
创建两个队列QA和QB,两者队列TTL分别设置为10S和40S,然后在创建一个交换机X和死信交换机Y,它们的类型都是direct,创建一个死信队列QD,它们的绑定关系如下
代码结构:
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.adx</groupId>
<artifactId>dead_message_queue</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dead_message_queue</name>
<description>dead_message_queue</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置文件
spring:
application:
name: deadMessage
rabbitmq:
host: host
port: 5672
username: ems
password: ems
virtual-host: /ems
listener:
type: simple
simple:
#这里记得将default-requeue-rejected属性设置为false
default-requeue-rejected: false
acknowledge-mode: manual
配置类
package com.adx.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class TtlQueueConfig {
public static final String X_EXCHANGE="X";
public static final String QUEUE_A="QA";
public static final String QUEUE_B="QB";
public static final String Y_DEAD_LETTER_EXCHANGE="Y";
public static final String DEAD_LETTER_QUEUE="QD";
//声明XExchange
@Bean("xExchange")
public DirectExchange xExchange(){
return new DirectExchange(X_EXCHANGE);
}
//声明YExchange
@Bean("YExchange")
public DirectExchange YExchange(){
return new DirectExchange(Y_DEAD_LETTER_EXCHANGE);
}
//声明队列A TTL为10s,并绑定到对应的死信交换机
@Bean("queueA")
public Queue queueA(){
Map<String,Object> args=new HashMap<String, Object>(3);
//声明当前队列绑定的死信交换机
args.put("x-dead-letter-exchange", Y_DEAD_LETTER_EXCHANGE);
//声明当前队列的死信路由key
args.put("x-dead-letter-routing-key", "YD");
//声明队列的TTL
args.put("x-message-ttl", 10000);
return QueueBuilder.durable(QUEUE_A).withArguments(args).build();
}
// 声明队列A绑定X交换机
@Bean
public Binding queueABindingX(@Qualifier("queueA") Queue queue,
@Qualifier("xExchange")DirectExchange exchange)
{
return BindingBuilder.bind(queue).to(xExchange()).with("XA");
}
//声明队列B ttl为40s,并绑定到对应的死信交换机
@Bean("queueB")
public Queue queueB()
{
Map<String,Object> args=new HashMap<String, Object>(3);
//声明当前队列绑定的死信交换机
args.put("x-dead-letter-exchange", Y_DEAD_LETTER_EXCHANGE);
//声明当前队列的死信路由key
args.put("x-dead-letter-routing-key", "YD");
//声明队列的TTL
args.put("x-message-ttl", 40000);
return QueueBuilder.durable(QUEUE_B).withArguments(args).build();
}
//声明队列B绑定X交换机
@Bean
public Binding queueBBindingX(@Qualifier("queueB") Queue queueB,
@Qualifier("xExchange") DirectExchange xExchange){
return BindingBuilder.bind(queueB).to(xExchange).with("XB");
}
//声明死信队列QD
@Bean("queueD")
public Queue queueD()
{
return new Queue(DEAD_LETTER_QUEUE);
}
//声明死信队列QD绑定关系
@Bean
public Binding deadLetterBindingQAD(@Qualifier("queueD") Queue queue,
@Qualifier("YExchange") DirectExchange exchange)
{
return BindingBuilder.bind(queue).to(exchange).with("YD");
}
}
消息生产者 :
package com.adx.sender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RequestMapping("ttl")
@RestController
public class Produce01 {
private static final Logger logger = LoggerFactory.getLogger(Produce01.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping("sendMsg/{message}")
public void sendMsg(@PathVariable String message)
{
logger.info("当前时间:{},发送一条消息给俩个TTL队列:{}", new Date(),message);
rabbitTemplate.convertAndSend("X","XA","消息来于10s"+message);
rabbitTemplate.convertAndSend("X","XB","消息来于40s"+message);
}
}
消息消费者:
package com.adx.receiver;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Date;
@Component
public class Consumer {
private static final Logger logger = LoggerFactory.getLogger(Consumer.class);
/**
* 没有人消费普通队列,这时候消息过期就跑到死信队列里面了
*
* @param message
* @param channel
*/
@RabbitListener(queues = "QD")
public void receiveD(Message message, Channel channel) throws IOException {
System.out.println("*****************************");
String s = new String(message.getBody());
logger.info("当前时间{},死信队列接收到消息---->{}", new Date(), s);
//手动ack
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
System.out.println("*****************************");
}
/**
* 如果有队列正常消费,就不会跑到死信队列
*/
//@RabbitListener(queues = "QA")
//public void receiveA(Message message, Channel channel)
//{
// System.out.println("*****************************");
// String s = new String(message.getBody());
// logger.info("当前时间{},A队列正常接收到消息---->{}",new Date(),s);
// System.out.println("*****************************");
//}
///**
// * 如果有队列正常消费,就不会跑到死信队列
// */
//@RabbitListener(queues = "QB")
//public void receiveB(Message message, Channel channel)
//{
// System.out.println("*****************************");
// String s = new String(message.getBody());
// logger.info("当前时间{},B队列正常接收到消息---->{}",new Date(),s);
// System.out.println("*****************************");
//}
/**
* A队列拒绝接收消息
* 注意:channel.basicReject(deliveryTag,requeue);
* basic.reject只能拒绝一条消息。拒绝批量消息则需要basicNack这个命令
* channel.basicNack(deliveryTag,true,true);
*/
@RabbitListener(queues = "QA")
public void rejectReceiveA(Message message, Channel channel) throws IOException {
System.out.println("*****************************");
String s = new String(message.getBody());
logger.info("当前时间{},A队列拒绝接收到消息---->{}", new Date(), s);
System.out.println("*****************************");
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}
/**
* A队列拒绝接收消息
*
* @param message
* @param channel
*/
@RabbitListener(queues = "QB")
public void rejectReceiveB(Message message, Channel channel) throws IOException {
System.out.println("*****************************");
String s = new String(message.getBody());
logger.info("当前时间{},A队列拒绝接收到消息---->{}", new Date(), s);
System.out.println("*****************************");
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}
}
发送消息:
控制台显示如下:测试例子中没有写A,B队列的消费者,所以消息再到达指定时间后,就会变成死信队列被消费.
我们可以测试,为AB队列指定消费者,则死信队列则没有消息可消费.
/**
* 如果有队列正常消费,就不会跑到死信队列
*/
@RabbitListener(queues = "QA")
public void receiveA(Message message, Channel channel)
{
System.out.println("*****************************");
String s = new String(message.getBody());
logger.info("当前时间{},A队列正常接收到消息---->{}",new Date(),s);
System.out.println("*****************************");
}
/**
* 如果有队列正常消费,就不会跑到死信队列
*/
@RabbitListener(queues = "QB")
public void receiveB(Message message, Channel channel)
{
System.out.println("*****************************");
String s = new String(message.getBody());
logger.info("当前时间{},B队列正常接收到消息---->{}",new Date(),s);
System.out.println("*****************************");
}
如果AB队列拒绝消费消息,则消息也会被投递到死信队列
/**
* A队列拒绝接收消息
* 注意:channel.basicReject(deliveryTag,requeue);
* basic.reject只能拒绝一条消息。拒绝批量消息则需要basicNack这个命令
* channel.basicNack(deliveryTag,true,true);
*/
@RabbitListener(queues = "QA")
public void rejectReceiveA(Message message, Channel channel) throws IOException {
System.out.println("*****************************");
String s = new String(message.getBody());
logger.info("当前时间{},A队列拒绝接收到消息---->{}", new Date(), s);
System.out.println("*****************************");
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}
/**
* A队列拒绝接收消息
*
* @param message
* @param channel
*/
@RabbitListener(queues = "QB")
public void rejectReceiveB(Message message, Channel channel) throws IOException {
System.out.println("*****************************");
String s = new String(message.getBody());
logger.info("当前时间{},A队列拒绝接收到消息---->{}", new Date(), s);
System.out.println("*****************************");
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}