🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # 多方测试 ⼀个发送者和 N 个接收者或者 N 个发送者和 N 个接收者会出现什么情况呢? ## 一对多发送 ### 注册队列 ~~~ package com.jdxia.rabbitmq; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; //定义队列 @Configuration public class RabbitConfig { @Bean public Queue neoQueue() { return new Queue("neo"); } } ~~~ ### 发送者 一个发送者 ~~~ import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class NeoSender { @Autowired private AmqpTemplate rabbitTemplate; public void send(int i) { String context = "spirng boot neo queue"+" ****** "+i; System.out.println("Sender1 : " + context); this.rabbitTemplate.convertAndSend("neo", context); } } ~~~ ### 接收者 接收者 1 示例,接收者 2 和 1基本⼀致 ~~~ import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @RabbitListener(queues = "neo") public class NeoReceiver1 { @RabbitHandler public void process(String neo) { System.out.println("Receiver 1: " + neo); } } ~~~ ### 测试 我们设计了⼀个发送者,两个接收者,发送⼀百个消息看看效果. ⼀个发送者,N 个接收者,经过测试接收端均匀接收到消息,也说明接收端⾃动进⾏了**均衡负载**,我们也可以利⽤这个特性做流量分发。 ~~~ @Autowired private NeoSender neoSender; @Test public void test() throws InterruptedException { for (int i = 0; i < 100; i++) { neoSender.send(i); } Thread.sleep(10000l); } ~~~ ~~~ Sender1 : spirng boot neo queue ****** 99 Receiver 1: spirng boot neo queue ****** 0 Receiver 2: spirng boot neo queue ****** 1 Receiver 1: spirng boot neo queue ****** 2 Receiver 2: spirng boot neo queue ****** 3 Receiver 1: spirng boot neo queue ****** 4 Receiver 2: spirng boot neo queue ****** 5 ~~~ ## 多对多发送 复⽤以上的发送者和接收者,再增加⼀个发送者 2 加⼊标记,在⼀百个循环中相互交替发送。 发送者⽅法如下: ~~~ public void send(int i) { String context = "spirng boot neo queue"+" ****** "+i; System.out.println("Sender2 : " + context); this.rabbitTemplate.convertAndSend("neo", context); } ~~~ ### 测试 发送端交替发送消息,接收端仍然会均匀接收到消息 ~~~ @Autowired private NeoSender neoSender; @Autowired private NeoSender2 neoSender2; @Test public void test() throws InterruptedException { for (int i = 0; i < 100; i++) { neoSender.send(i); neoSender2.send(i); } Thread.sleep(10000l); } ~~~ ~~~ Receiver 2: Spring boot neo queue ****** 0 Receiver 1: Spring boot neo queue ****** 0 Receiver 2: Spring boot neo queue ****** 1 Receiver 1: Spring boot neo queue ****** 1 Receiver 2: Spring boot neo queue ****** 2 Receiver 1: Spring boot neo queue ****** 2 ~~~