SpringAMQP 发布订阅-TopicExchange

根据这个模型编写代码:

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "topic.queue1"),
                    exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
                    key = {"china.#"}
            )
    )
    public void listenTopicQueue1(String msg){
        System.out.println("从topic.queue1中获取到了消息:"+msg);
    }

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "topic.queue2"),
                    exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
                    key = {"#.news"}
            )
    )
    public void listenTopicQueue2(String msg){
        System.err.println("从topic.queue2中获取到了消息:"+msg);
    }

pulsher发送消息代码:

@Test
    public void testTopicExchangeSend() {
        //发送消息
        String DirectChangeName = "itcast.topic";//交换机的名字
        String msg = "这里是天气预报";
        rabbitTemplate.convertAndSend(DirectChangeName, "weather.news", msg);
    }

用@RabbitListener注解实现交换机和队列的绑定以及BingingKey的设置,TopicExchange的特点就是可以用正则表达式匹配,可以看到队列1的RoutingKey China.# 的意思接收消息的前提是china.开头。#.news 的意思是该队列接收消息的前提是以 .news结尾。

 这里看我发送消息的RoutingKey是china.news 这两个队列都满足了请求 所有都接收到了

这里看我改了一下 第二个队列不匹配 所以就没接收到消息

这里的末尾是news  只有第二个队列匹配到了 所以第二个队列接收。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值