- 引入Jar包
这里使用的是gradle配置
compile('org.springframework.boot:spring-boot-starter-amqp')
- 配置application.properties
spring.rabbitmq.addresses = localhost:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
- 配置config
/**
* @Description: 消息队列配置类
* @Author: zw
*/
@Configuration
public class RabbitConfig {
/**
* 死信队列跟交换机类型没有关系 不影响该类型交换机的特性.
*/
@Bean
DirectExchange deadLetterExchange(){
return new DirectExchange("Dead_Letter_Exchange");
}
/**
* 声明一个死信队列.
* x-dead-letter-exchange 对应死信交换机转发交换机名
* x-dead-letter-routing-key 对应死信队列转发路由名
*/
@Bean
Queue deadLetterQueue(){
Map<String, Object> map = new HashMap<String, Object>(2);
map.put("x-dead-letter-exchange","Dead_Letter_Exchange");
map.put("x-dead-letter-routing-key","redirect.routing.key");
return new Queue("Dead_Letter_Queue",true,false,false,map);
}
/**
* 定义死信队列转发队列.
*/
@Bean
public Queue redirectQueue() {
return new Queue("REDIRECT_QUEUE");
}
/**
* 死信路由通过 DL_KEY 绑定键绑定到死信队列上.
*/
@Bean
public Binding deadLetterBinding(){
return new Binding("Dead_Letter_Queue",Binding.DestinationType.QUEUE,"Dead_Letter_Exchange","dead.letter.routing.key",null);
}
@Bean
public Binding redirectBinding(){
return new Binding("REDIRECT_QUEUE",Binding.DestinationType.QUEUE,"Dead_Letter_Exchange","redirect.routing.key",null);
}
- 申明一个交换机
- 配置一个死信队列,并设置死信队列过期消息进行转发的交换机参数和路由键
- 将死信队列与交换机进行绑定
- 申明一个作为死信队列转发消息的队列
- 将转发队列与死信队列之前设置参数的交换机和路由键进行绑定
测试:
@RabbitListener(queues = "REDIRECT_QUEUE")
public void process(Message msg, Channel channel) throws IOException {
System.out.println("进入myQueue时间为"+new Date().toLocaleString());
public void sendDirectMsg(Object msg){
CorrelationData correlationData =new CorrelationData(UUID.randomUUID().toString());
System.out.println("消息id" + correlationData.getId());
MessagePostProcessor messagePostProcessor = message -> {
MessageProperties messageProperties = message.getMessageProperties();
//设置编码
messageProperties.setContentEncoding("utf-8");
//设置过期时间10*1000毫秒
messageProperties.setExpiration("10000");
return message;
};
rabbitTemplate.convertAndSend("Dead_Letter_Exchange","dead.letter.routing.key",msg,messagePostProcessor,correlationData);
}
观察MQ监控平台
由图可见,消息一开始被路由到死信队列,因为没有消费者监听所以当消息的过期时间到了之后被私信队列投递路由到之前设置好的转发队列。