rabbitmq 高级特性 死信队列(死信交换机)

概念

信息成为死信的3种情况

代码实现

实现死信队列需要一组正常队列和交换机 以及死信队列和死信交换机
但是声明死信交换机和队列和正常声明一致
最关键的是在声明要被处理的正常队列给出两个参数(deadLetterExchange,deadLetterRoutingKey)来绑定关系

package com.jie.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    public static final String QUEUE_NAME = "boot_queue";

    public static final String DLX_EXCHANGE_NAME = "dlx_boot_topic_exchange";
    public static final String DLX_QUEUE_NAME = "dlx_boot_queue";
    //交换机
    @Bean("bootExchange")
    public Exchange bootExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }
    //队列
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder
                .durable(QUEUE_NAME)
                //绑定对应的死信交换机
                .deadLetterExchange(DLX_EXCHANGE_NAME)
                //死信交换机设置的key为dlx.# 这里我们任意给出一个能被匹配的
                .deadLetterRoutingKey("dlx.hh")
                //设置10秒过期时间
                .ttl(10000)
                .build();
    }
    //绑定关系
    @Bean
    public Binding bingQueueExchange(@Qualifier("bootQueue") Queue queue,@Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }

    //死信交换机
    @Bean("bootDlxExchange")
    public Exchange bootDlxExchange(){
        return ExchangeBuilder.topicExchange(DLX_EXCHANGE_NAME).durable(true).build();
    }
    //死信队列
    @Bean("bootDlxQueue")
    public Queue bootDlxQueue(){
        return QueueBuilder.durable(DLX_QUEUE_NAME).build();
    }
    //绑定死信队列和死信交换机关系
    @Bean
    public Binding commonDeadLetterExchange(@Qualifier("bootDlxQueue")Queue queue,@Qualifier("bootDlxExchange")Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("dlx.#").noargs();
    }
}

测试过期时间 死信队列

在上面声明中我们已经吧正常队列定义为TTL队列 过期时间为10秒 我们发信息测试一下

    @Test void send(){
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","10秒后我就死了呜呜呜 "+i);
        }
    }

信息未过期时 信息在原先的队列

10秒后信息过期 于是触发死信机制 队列给绑定的死信交换机发送消息 对应的路由key为dlx.hh(上面配置定义的)

而死信交换机和死信队列绑定的路由Key为dlx.# 于是被匹配到 消息成功进到死信队列里面

其他两种情况

另外两种触发条件为 超过消息队列长度 那么新进来的消息就会直接触发死信机制
消费者在手动确认模式 拒绝接受 同时设置不重新回到队列 也会触发死信机制
可自行测试

posted @ 2021-10-06 14:40  一个经常掉线的人  阅读(190)  评论(0编辑  收藏  举报