ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

RabbitMQ之死信交换机(延迟队列)

2022-02-28 17:04:26  阅读:162  来源: 互联网

标签:return 队列 RabbitMQ 死信 交换机 import public


死信队列(延迟队列)

死信,在官网中对应的单词为“Dead Letter”,它是 RabbitMQ 的一种消息机制。
般来说,生产者将消息投递到 broker 或者直接到 queue 里了,consumer 从 queue 取出消息进行消费,如果它一直无法消费某条数据,那么可以把这条消息放入死信队列里面。等待 
条件满足了再从死信队列中取出来再次消费,从而避免消息丢失。
死信消息来源:
        1.消息 TTL 过期
        2.队列满了,无法再次添加数据
        3.消息被拒绝(reject 或 nack),并且 requeue =false

 

订单的超时处理

后超时的订单消息到正常交换机exchange-a中,消息匹配到队列queue-a,但一分钟后仍未消费。

消息会被投递到死信交换机dlx-exchange中,并发送到死信队列中;

死信队列dlx-exchange的消费者拿到消息后,根据消息去查询订单的状态,如果仍然是未支付状态,将订单状态更新为超时状态。
 

代码

 DeadConfig类

注意:死信交换机就是一台普通的交换机!!!

package com.example.provider.mq;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@SuppressWarnings("all")
public class DeadConfig {

    //1.需要正常的交换机
    //2.正常的队列发出消息(具备配置)
    //3.具备死信交换机,死信队列

    @Bean
    public Queue normalQueue(){
        Map<String,Object> config=new HashMap<>();
        //设置过期时间
        config.put("x-message-ttl",10000);
        //死信交换机
        config.put("x-dead-letter-exchange", "deadExchange");
        //死信routingkey
        config.put("x-dead-letter-routing-key", "DD");
        return new Queue("normalQueue",true,false,false,config);
    }

    @Bean
    public Queue deadQueue(){
        return new Queue("deadQueue",true);
    }

    @Bean
    public DirectExchange normalExchange(){
        return new DirectExchange("normalExchange");
    }

    //死信交换机就是一台正常的交换机
    @Bean
    public DirectExchange deadExchange(){
        return new DirectExchange("deadExchange");
    }

    @Bean
    public Binding normalBinding(){
        return BindingBuilder.bind(normalQueue()).to(normalExchange()).with("CC");
    }

    @Bean
    public Binding deadBinding(){
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with("DD");
    }



}

ProviderController类

 @RequestMapping("/deadSend")
    public String deadSend(){
        //保存了一个订单
        template.convertAndSend("normalExchange","CC","order-1109");
        return "yes";
    }

发送数据 

 上图可以看到

normalQueue队列有一个正常的消息,但是我代码里面设定了十秒钟的过期时间,之前死信队列还只有两台消息

 上图可知现在deadQueue已经变成三条了,死信完成,希望能帮助你们

bye~

标签:return,队列,RabbitMQ,死信,交换机,import,public
来源: https://blog.csdn.net/Cat_Jay_Fish/article/details/123184225

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有