嘻哈飞车族腻害,高人都是这样玩SpringBoot整合RabbitMQ( 二 )

(2)消费者
@Componentpublic class DirectReceiver {// 监听队列@RabbitListener(queues = "hello.yolo")public void handler1(String msg) {System.out.println("handler1>>>" + msg);}}12345678(3)测试:生产者
@AutowiredRabbitTemplate rabbitTemplate;@Testpublic void contextLoads() {//将消息转发到 routingKey 为 hello.yolo 的队列 , 对应 DirectReceiver 的监听队列名rabbitTemplate.convertAndSend("hello.yolo", "hello yolo! ni hao!");}1234567
可以参考:
简单的讲 , 就是把交换机(Exchange)里的消息发送给所有绑定该交换机的队列 , 忽略routingKey 。
嘻哈飞车族腻害,高人都是这样玩SpringBoot整合RabbitMQ
本文插图
由图可知 , 生产者把消息发送到交换机后 , 由交换机发送给消费者队列 。 消费者队列如果想要接收到交换机里的消息 , 那么需要保证:队列绑定的交换机名称要和交换机一致 , 这个是广播模式的关键 , 也是MQ后续所有模式最粗略的前提 。
这里消息是通过生产者发往交换机的 , 然后交换机再发送给绑定的队列(1)配置广播模式
@Configurationpublic class RabbitFanoutConfig {public static final String FANOUTNAME = "yolo-fanout";/*** 队列1* @return*/@BeanQueue queueOne() {return new Queue("queue-one");}/*** 队列2* @return*/@BeanQueue queueTwo() {return new Queue("queue-two");}/*** 交换机* @return*/@BeanFanoutExchange fanoutExchange() {return new FanoutExchange(FANOUTNAME, true, false);}/*** 绑定队列1* @return*/@Beanorg.springframework.amqp.core.Binding bindingOne() {return BindingBuilder.bind(queueOne()).to(fanoutExchange());}/*** 绑定队列2* @return*/@BeanBinding bindingTwo() {return BindingBuilder.bind(queueTwo()).to(fanoutExchange());}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849(2)消费者
/** * 定义接收器:消费者 */@Componentpublic class FanoutReceiver {/*** 接收消息队列1* @param msg*/@RabbitListener(queues = "queue-one")public void handler1(String msg) {System.out.println("FanoutReceiver:handler1:" + msg);}/*** 接收消息队列2* @param msg*/@RabbitListener(queues = "queue-two")public void handler2(String msg) {System.out.println("FanoutReceiver:handler2:" + msg);}}12345678910111213141516171819202122(3)测试:生产者
/*** 往交换机上发送信息*/@Testpublic void test1() {rabbitTemplate.convertAndSend(RabbitFanoutConfig.FANOUTNAME,null,"hello fanout!");}1234567这里需要注意 , 需要先启动消费者 , 再启动生产者 , 否则先启动生产者 , exchange接收到消息后发现没有队列对其感兴趣 , 就会将消息丢掉 , 此时跟 routingKey 无关
队列1和队列2 均收到了消息
嘻哈飞车族腻害,高人都是这样玩SpringBoot整合RabbitMQ
本文插图
可参考:
假如你想在淘宝上买一双运动鞋 , 那么你是不是会在搜索框中搜“XXX运动鞋” , 这个时候系统将会模糊匹配的所有符合要求的运动鞋 , 然后展示给你 。 所谓“主题路由匹配交换机”也是这样一个道理 , 但是使用时也有一定的规则 。
String routingkey = “testTopic.#”;String routingkey = “testTopic.*”;12* 表示只匹配一个词#表示匹配多个词


推荐阅读