SpringAMQP交换机:Topic

Topic与Direct类似,区别在于topic的routingKey必须时多个单词的列表,并且用.分割。

例如 china.news china.weather

Queue和Exchange指定BindingKey时候可以使用通配符。

#:0或者多个单词    *:代指一个单词

1.利用@RabbitListener声明exchange queue RoutingKey

@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("1接收到direct.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("2接收到topic.queue2:【"+msg+"】");
    }

2.在consumer服务中,编写两个消费者方法,在listener中分别监听topic.queue1 和topic.queue2

3.在publisher中编写测试方法,向itcast.topic发送消息

@Test
    public void testSendTopicMessage(){
        String exchangeName = "itcast.topic";
        String message = "手机卡艾丽卡睡觉了";
        rabbitTemplate.convertAndSend(exchangeName,"china.weather", message);
    }

 

posted @ 2021-11-11 09:52  zuiAI0658  阅读(93)  评论(0)    收藏  举报