rabbitMQ五种消息发送模式——通配符模式

紧接上一篇:https://blog.csdn.net/qq_36357242/article/details/107688368

本篇介绍通配符模式

通配符模式

通配符模式是可以根据路由键匹配规则选择性给多个消费者发送消息的模式,它包含一个生产者、两个消费者、两个队列和一个交换机。两个消费者同时绑定到不同的队列上去,两个队列通过路由键匹配规则绑定到交换机上去,生产者发送消息到交换机,交换机通过路由键匹配规则转发到不同队列,队列绑定的消费者接收并消费消息。

 

 

  • *:只能匹配一个单词;
  • #:可以匹配零个或多个单词。

声明交换机和队列

    //声明通配符模式交换机
    @Bean
    public TopicExchange topic() {
        return new TopicExchange("exchange.topic");
    }
    //声明俩个通配符模式队列
    @Bean
    public Queue topicQueue1() {
        return new Queue("topic1");//队列一
    }
    @Bean
    public Queue topicQueue2() {
        return new Queue("topic2");//队列二
    }

    //将队列队列一绑定到交换机
    @Bean
    public Binding topicBinding1a(TopicExchange topic, Queue topicQueue1) {
        return BindingBuilder.bind(topicQueue1).to(topic).with("*.orange.*");
    }
    @Bean
    public Binding topicBinding1b(TopicExchange topic, Queue topicQueue1) {
        return BindingBuilder.bind(topicQueue1).to(topic).with("*.*.rabbit");
    }
    //将队列队列二绑定到交换机
    @Bean
    public Binding topicBinding2a(TopicExchange topic, Queue topicQueue2) {
        return BindingBuilder.bind(topicQueue2).to(topic).with("lazy.#");
    }

创建生产者(发送者)

    //创建消息发送者
    public void sendToTopic(String index) {
        String context = "通配符模式发送的消息";
        System.out.println("通配符模式发送者: " + context);
        this.rabbitTemplate.convertAndSend("exchange.topic", index,context+":"+index);
    }

创建消费者(接收者) 

    @RabbitListener(queues = "topic1")
    @RabbitHandler
    public void process8(String topic) {
        System.err.println("通配符模式 消费者1: " + topic);
    }

    @RabbitListener(queues = "topic2")
    @RabbitHandler
    public void process9(String topic) {
        System.out.println("通配符模式 消费者2: " + topic);
    }

运行

    //通配符模式
    @Test
    public void contextLoads5() {
        senderConfig.sendToTopic("lazy.111");
        senderConfig.sendToTopic("111.orange.111");
        senderConfig.sendToTopic("1111.111.orange");
        senderConfig.sendToTopic("1111.111.rabbit");
        senderConfig.sendToTopic("1111.rabbit");
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

答 案

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值