DirectExchange交换机简单入门demo

源码在文章末尾👇🏻

前置学习知识

1. FanoutExchange交换机代码教程 SpringAMQP 简单入门demod​​​​​​​2

了解过Fanout交换机的同学就一定知道, 在给Fanout交换机发送消息的时候只需要指定交换机的名称, 和要发送的消息即可, 并且可以指定多个队列  FanoutExchange交换机代码教程

    @Test
    public void testSendFanoutExchange() {
        // 交换机名称
        String exchangeName = "声明FanoutExchange交换机";
        // 消息
        String message = "测试 FanoutExchange 交换机, 请各位接收 !";
        rabbitTemplate.convertAndSend(exchangeName, "", message);
    }

下面我们要学习的Direct交换机的区别, 和Fanout很相似, 但是唯一不同的就是每一个Queue都与Exchange设置一个BindingKey, 而且在发布消息的时候也需要指定消息的RoutingKey

下面我们用代码演示一下

    @RabbitListener(bindings = @QueueBinding(
            //队列名称
            value = @Queue("direct.queue1"),
            //交换机名称
            exchange = @Exchange(value = "direct", type = ExchangeTypes.DIRECT),
            //key
            key = {"red", "blue"}
    ))
    public void listenDirectQueue1(String msg){
        System.out.println("消费者接收到fanout.queue1的消息:【" + msg + "】");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("direct.queue2"),
            exchange = @Exchange(value = "direct"),
            key = {"red", "yellow"}
    ))
    public void listenDirectQueue2(String msg){
        System.out.println("消费者接收到fanout.queue1的消息:【" + msg + "】");
    }

案例1 key的值为blue

    @Test
    public void testSendDirectExchange() {
        // 交换机名称
        String exchangeName = "direct";
        // 消息
        String red = "hello, blue!";
        rabbitTemplate.convertAndSend(exchangeName, "blue", red);
    }

运行结果 :

 解析: 

其实原因很简单 在我们的QueueBinding中声明的key中包含了 "blue"

 案例2 key值为red

    @Test
    public void testSendDirectExchange() {
        // 交换机名称
        String exchangeName = "direct";
        // 消息
        String red = "hello, red!";
        rabbitTemplate.convertAndSend(exchangeName, "red", red);
    }

运行结果 :
​​​​​​​解析 : 

 我们能看出, 这次由两个队列同时接收到了消息, 在队列direct.queue1和direct.queue2中, QueueBinding中声明的key同时都包含了 "red"

 源码项目地址:

链接: https://pan.baidu.com/s/1vnYVEPGO8B5XLCf9Xc67cA 提取码: few9

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Max恒

为了开源加油 ! !

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值