300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > SpringAMQP--DirectExchange

SpringAMQP--DirectExchange

时间:2024-01-19 04:57:29

相关推荐

SpringAMQP--DirectExchange

Direct

在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。

在Direct模型下:

队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)

消息的发送方在 向 Exchange发送消息时,也必须指定消息的RoutingKey

Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行判断,只有队列的Routingkey与消息的Routing key完全一致,才会接收到消息

案例需求如下

利用@RabbitListener声明Exchange、Queue、RoutingKey

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

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

基于注解声明队列和交换机

基于@Bean的方式声明队列和交换机比较麻烦,Spring还提供了基于注解方式来声明。

在consumer的SpringRabbitListener中添加两个消费者,同时基于注解来声明队列和交换机:

@RabbitListener(bindings = @QueueBinding(value = @Queue(name = "direct.queue1"),exchange = @Exchange(name = "leon.direct", type = ExchangeTypes.DIRECT),key = {"red", "blue"}))public void listenDirectQueue1(String msg){System.out.println("消费者接收到direct.queue1的消息:【" + msg + "】");}@RabbitListener(bindings = @QueueBinding(value = @Queue(name = "direct.queue2"),exchange = @Exchange(name = "leon.direct", type = ExchangeTypes.DIRECT),key = {"red", "yellow"}))public void listenDirectQueue2(String msg){System.out.println("消费者接收到direct.queue2的消息:【" + msg + "】");}

消息发送

在publisher服务的SpringAmqpTest类中添加测试方法:

@Testpublic void testSendDirectExchange() {// 交换机名称String exchangeName = "leon.direct";// 消息String message = "红色警报!日本乱排核废水,导致海洋生物变异,惊现哥斯拉!";// 发送消息rabbitTemplate.convertAndSend(exchangeName, "red", message);}

总结

描述下Direct交换机与Fanout交换机的差异?

Fanout交换机将消息路由给每一个与之绑定的队列

Direct交换机根据RoutingKey判断路由给哪个队列

如果多个队列具有相同的RoutingKey,则与Fanout功能类似

基于@RabbitListener注解声明队列和交换机有哪些常见注解?

@Queue

@Exchange

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。
相关阅读
SpringAMQP--基本介绍

SpringAMQP--基本介绍

2020-05-03

springAMQP

springAMQP

2021-11-11

3.SpringAMQP

3.SpringAMQP

2019-05-17

SpringAMQP详解

SpringAMQP详解

2020-03-03

扩展阅读