使用SpringAMQP实现发布订阅模型之Topic Exchange
Topic Exchange:主题
一、主题模式
TopicExchange 与 DirectExchange 类似,区别在于
routingKey
必须是多个单词的列表,并且以 . 分割。
Queue 与 Exchange 指定BindingKey
时可以使用通配符:
#
:代指0个或多个单词*
:代指一个单词
例如:
Queue1:绑定的是
china.#
,因此凡是以china.
开头的routing key
都会被匹配到。包括 china.news 和 china.weather
Queue2:绑定的是#.news
,因此凡是以.news
结尾的routing key
都会被匹配。包括 china.news 和 japan.news
二、模拟计划
利用 @RabbitListener 声明 Exchange、Queue、RoutingKey,其中 topic.queue1 的 bindingKey 为 “china.#”,topic.queue2 的 bindingKey 为 “#.news”
在 consumer 服务中,编写两个消费者方法,分别监听 topic.queue1 和 topic.queue2
在 publisher 中编写测试方法,向 gentlebrother. topic 发送消息
三、模拟Topic
1.基于注解声明队列和交换机
在 consumer 服务中,编写两个消费者方法,分别监听 topic.queue1 和topic.queue2,并利用 @RabbitListener 声明 Exchange、Queue、RoutingKey
package cn.itcast.mq.listener;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.lang.model.type.ExecutableType;
import java.time.LocalTime;
import java.util.Locale;
/**
* @author 温柔哥
* @create 2024-02-01 16:01
*/
@Component
public class SpringRabbitListener {
// 模拟发布订阅模型之 Topic
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue1"),
exchange = @Exchange(name = "gentlebrother.topic", type = ExchangeTypes.TOPIC),
key = "china.#"
))
public void listenTopicQueue1(String message) {
System.out.println("消费者1接受到 topic.queue1 的消息:【" + message + "】");
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue2"),
exchange = @Exchange(name = "gentlebrother.topic", type = ExchangeTypes.TOPIC),
key = "#.news"
))
public void listenTopicQueue2(String message) {
System.out.println("消费者2接受到 topic.queue2 的消息:【" + message + "】");
}
}
启动 consumer 服务,到 mq 客户端查看声明队列、交换机和绑定 key 是否成功
2.测试发送者发送消息
在 publisher 服务的 SpringAmqpTest 类中添加测试方法:
// 测试发布订阅模型之 Topic
@Test
public void testTopicExchange1() {
String exchangeName = "gentlebrother.topic";
String message = "i am china.news!";
rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
}
@Test
public void testTopicExchange2() {
String exchangeName = "gentlebrother.topic";
String message = "i am china.weather!";
rabbitTemplate.convertAndSend(exchangeName, "china.weather", message);
}
分别启动这两个测试方法
3.分析结果
很明显:
当发送者给队列发送消息时绑定的 routingKey 为 “china.news” 时,队列1和队列2绑定的 bindingKey 都匹配,故消费者1和消费者2都可以接收到消息
当发送者给队列发送消息时绑定的 routingKey 为 “china.weather” 时,只有队列1绑定的 bindingKey 与之相匹配,故消费者1可以接收到消息
四、总结
1.Direct交换机与Topic交换机的差异?
Topic 交换机接收的消息 RoutingKey 必须是多个单词,以
**.**
分割
Topic 交换机与队列绑定时的 bindingKey 可以指定通配符
2.Topic交换机可以使用哪些通配符?
#
:代表0个或多个词*
:代表1个词