本文主要是介绍SpringAMQP发布、订阅——Fanout Exchange交换机代码模拟,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
发布订阅模型:
MQ提供了很多交换机模型 其中常用的有下边三个:
Fanout:广播
Direct:路由
Topic:话题
转换器只负责消息路由,不是存储,路由失败则消息丢失
Fanout Exchange:会将接收到的消息路由导每一个跟其绑定的queue.
利用SpringAMQP演示FanoutExchange的使用:
实现代码:
在consumer编写工具类,实现交换机和队列的绑定:
package cn.itcast.mq.configu;import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @className:cn.itcast.mq.configu.BindExchangeToQueue* @description:by-li* @author:Administrator* @create:2024-05-1116:33*/
@Configuration
public class BindExchangeToQueue {//声明交换机@Beanpublic FanoutExchange fanoutExchange() {return new FanoutExchange("itcast.fanout");}//生命queue@Beanpublic Queue fanoutqueue1() {return new Queue("itcast.queue1");}@Beanpublic Queue fanoutqueue2() {return new Queue("itcast.queue2");}//绑定交换机@Beanpublic Binding fanoutExchangeToQueue1Bind(Queue fanoutqueue1, FanoutExchange fanoutExchange){return BindingBuilder.bind(fanoutqueue1).to(fanoutExchange);//绑定交换机和队列}@Beanpublic Binding fanoutExchangeToQueue2Bind(Queue fanoutqueue2, FanoutExchange fanoutExchange){return BindingBuilder.bind(fanoutqueue2).to(fanoutExchange);//绑定交换机和队列}}
在consumer实体类里编写接收两个队列请求的方法:
@RabbitListener(queues = "itcast.queue1")public void lintestFanoutExchangeToQueue1(String mes) throws InterruptedException {System.out.println("从队列1中获取到了消息:"+mes);Thread.sleep(200);}@RabbitListener(queues = "itcast.queue2")public void lintestFanoutExchangeToQueue2(String mes) throws InterruptedException {System.out.println("从队列2中获取到了消息:"+mes);Thread.sleep(200);}
在publisher里编写测试方法 模拟给交换机发送消息:
//给FanoutExchange交换机发送消息@Testpublic void testFanoutExchangeSend(){String FanoutChangeName = "itcast.fanout";String msg="我是fannout发送的消息";rabbitTemplate.convertAndSend(FanoutChangeName,"",msg);}
然后发送请求和启动consumer类,在控制台查看:
这里看到我们只发送了一条消息,但是两个consumer消费者都接收到了消息,能看出来Fanout Exchange交换机将收到的消息发到了给他绑定的两个queue里了
总结:
这篇关于SpringAMQP发布、订阅——Fanout Exchange交换机代码模拟的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!