springboot整合rabbitmq消息队列之死信队列

配置死信队列

/*
        死信队列
     */
    //1.声明正常交换机和队列

    public static final String NORMAL_DLX_QUEUE = "normal_dlx_queue";

    public static final String NORMAL_DLX_Exchange = "normal_dlx_exchange";

    //ttl
    private static final int NORMAL_DLX_EXPIRATION = 10000;

    //设置队列长度限制

    private static final int NORMAL_DLX_LENGTH = 10;


    public static final String DLX_QUEUE = "dlx_queue";

    public static final String DLX_Exchange = "dlx_exchange";


    //绑定死信队列

    @Bean
    public Queue normalDlxQueue(){
        return QueueBuilder.durable(NORMAL_DLX_QUEUE)
                .withArgument("x-dead-letter-exchange", DLX_Exchange)
                .withArgument("x-dead-letter-routing-key", "dlx.hehe")
                .withArgument("x-message-ttl", NORMAL_DLX_EXPIRATION)
                .withArgument("x-max-length",NORMAL_DLX_LENGTH)
                .build();
    }

    @Bean
    public TopicExchange normalDlxExchange(){
        return new TopicExchange(NORMAL_DLX_Exchange);
    }

    @Bean
    public Binding normalDlxBinding(){
        return BindingBuilder.bind(normalDlxQueue()).to(normalDlxExchange()).with("test.dlx.#");
    }

    //声明死信队列,和死信交换机




    @Bean
    public Queue dlxQueue(){
        return new Queue(DLX_QUEUE);
    }

    @Bean
    public TopicExchange dlxExchange(){
        return new TopicExchange(DLX_Exchange);
    }

    @Bean
    public Binding dlxBinding(){
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with("dlx.#");
    }

测试死信队列

@Test
    void DLX() {
        //1.测试时间过期
        //2.测试队列超长度
//        for (int i = 0; i < 20; i++) {
//            rabbitTemplate.convertAndSend(RabbitMQConfig.NORMAL_DLX_Exchange,"test.dlx.haha","hello jsp!");
//        }
        //3.测试消息拒收

        rabbitTemplate.convertAndSend(RabbitMQConfig.NORMAL_DLX_Exchange,"test.dlx.haha","hello jsp!");

    }

其中消息拒收代码

@Component
public class DlxListener {

   //死信队列,监听正常的队列

    @RabbitListener(queues = "normal_dlx_queue")
    public void myAckListener(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {


        try {
            System.out.println(message);
            System.out.println("处理业务逻辑...");

            /**
             * 无异常就确认消息
             * basicAck(long deliveryTag, boolean multiple)
             * deliveryTag:取出来当前消息在队列中的的索引;
             * multiple:为true的话就是批量确认,如果当前deliveryTag为5,那么就会确认
             * deliveryTag为5及其以下的消息;一般设置为false
             */
            int p =1/0;
            //手动签收
            channel.basicAck(tag, true);
        }catch (Exception e){
            /**
             * 有异常就绝收消息
             * basicNack(long deliveryTag, boolean multiple, boolean requeue)
             * requeue:true为将消息重返当前消息队列,还可以重新发送给消费者;
             *         false:将消息丢弃
             */
            System.out.println();
            //出现异常拒绝接受
            channel.basicNack(tag,true,false);
        }

    }

你可能感兴趣的:(springboot,rabbitmq)