发布订阅-Topic Exchange
TopicExchange与DirectExchange类似,区别在于routingKey必须是多个单词的列表,并以(.)分割。
案例 利用SpringAMQP演示TopicExchange的使用
第一步第二步实现代码:
/ //------------------------ topic ------------------------
@RabbitListener(bindings = @QueueBinding(
value = @Queue("topic.queue1"),
exchange = @Exchange(value = "itcast.topic", type = ExchangeTypes.TOPIC),
key = "china.#"
))
public void listenTopicQueue1(String msg) {
System.out.println("消费者接收到topic.queue1的消息: ["+ msg +"]");
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue("topic.queue2"),
exchange = @Exchange(value = "itcast.topic", type = ExchangeTypes.TOPIC),
key = "#.news"
))
public void listenTopicQueue2(String msg) {
System.out.println("消费者接收到topic.queue2的消息: ["+ msg +"]");
}
运行可以成功后返回MQ可以看到已经添加了一个itcast.topic
点击itcast.topic进去也能看到你设置的BindingKey
第三步实现代码如下(我的Routingkey为"hyq.news"与queue2的Bindingkey(#.news)匹配所以结果大家都可以猜到):
@Test
public void testSendTopicExchange() {
// 交换机名称
String exchangeName = "itcast.topic";
// 消息
String message = "hello, xxxx.news !";
//发送消息
rabbitTemplate.convertAndSend(exchangeName, "hyq.news", message);
}