根据这个模型编写代码:
@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发送消息代码:
@Testpublic 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 只有第二个队列匹配到了 所以第二个队列接收。