TopicExchange与DirectExchange类似,区别在于routingKey必须是多个单词的列表,并且以 . 分割。
Queue与Exchange指定BindingKey时可以使用通配符:
#:代指0个或多个单词
*:代指一个单词
案例:利用SpringAMQP演示TopicExchange的使用
实现思路如下:
1.
并利用
@RabbitListener
声明
Exchange
、
Queue
、
RoutingKey
2.
在
consumer
服务中,编写两个消费者方法,分别监听
topic.queue1
和
topic.queue2
3.
在
publisher
中编写测试方法,向
itcast
.
topic
发送消息
![](https://img-blog.csdnimg.cn/84392b6297f640f6bc3c3ecb598a8f40.png)
代码实现:
在consumer服务声明Exchange、Queue
1.
在
consumer
服务中,编写两个消费者方法,分别监听
topic
.queue1
和
topic
.queue2
,
2.
并利用
@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("TopicQueue1消费者接收到消息:【" + 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.out.println("TopicQueue2消费者接收到消息:【" + msg + "】");
}
在publisher服务发送消息到TopicExchange
在publisher服务的SpringAmqpTest类中添加测试方法:
@Test
public void testTopicExchange(){
//交换机名称
String exchangeName = "itcast.topic";
//发送消息
String message = "hello,Topic";
rabbitTemplate.convertAndSend(exchangeName,"Asia.news",message);
rabbitTemplate.convertAndSend(exchangeName,"china.news",message);
}
}