RabbitMQ交换机之死信交换机

续博客:RabbitMQ交换机之直连交换机,扇形交换机,主题交换机_小依不秃头的博客-CSDN博客

一、死信交换机(延迟队列)的概念 

 

 死信,在官网中对应的单词为“Dead Letter”,它是 RabbitMQ 的一种消息机制。

般来说,生产者将消息投递到 broker 或者直接到 queue 里了,consumer 从 queue 取出消息进行消费,如果它一直无法消费某条数据,那么可以把这条消息放入死信队列里面。等待
条件满足了再从死信队列中取出来再次消费,从而避免消息丢失。

死信消息来源:

  • 消息 TTL 过期
  • 队列满了,无法再次添加数据
  • 消息被拒绝(reject 或 nack),并且 requeue =false

二、死信交换机(代码)

①生产者,创建交换机

package com.xhy.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);//message在该队列queue的存活时间最大为10秒
        //死信交换机
        config.put("x-dead-letter-exchange", "deadExchange"); //x-dead-letter-exchange参数是设置该队列的死信交换器(DLX)
        //死信routingkey
        config.put("x-dead-letter-routing-key", "deadQueue");//x-dead-letter-routing-key参数是给这个DLX指定路由键

        return new Queue("normalQueue",true,false,false,config);
    }
    //死信
    @Bean
    public Queue daadQueue(){

        return new Queue("daadQueue",true);
    }
    //创建交换机---正常(死信交换机就是直连交换机)
    @Bean
    public DirectExchange normalExchange(){
        return  new DirectExchange("directExchange");
    }
    //死信
    @Bean
    public DirectExchange deadExchange(){
        return  new DirectExchange("deadExchange");
    }

    //进行交换机和队列的绑定
    //设置绑定key
//正常
@Bean
    public Binding normalBinding(){
        return  BindingBuilder.bind(normalQueue()).to(normalExchange()).with("CC");
    }
    //死信
@Bean
    public Binding deadBinding(){
        return  BindingBuilder.bind(normalQueue()).to(deadExchange()).with("DD");
    }



}

②创建controller层模拟发送消息

@RequestMapping("/deadSend")
public String deadSend(){
    //原理:假设保存一个订单
    template.convertAndSend("normalExchange","CC","order-110");
    return "yes";
}

③运行

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值