ToB企服应用市场:ToB评测及商务社交产业平台

标题: 利用java代码操作rabbitMQ收发消息 [打印本页]

作者: 美丽的神话    时间: 4 天前
标题: 利用java代码操作rabbitMQ收发消息
SpringAMQP

未来我们开发业务功能的时候,肯定不会在控制台收发消息,而是应该基于编程的方式。由于RabbitMQ采用了AMQP协议,因此它具备跨语言的特性。任何语言只要依照AMQP协议收发消息,都可以与RabbitMQ交互。并且RabbitMQ官方也提供了各种不同语言的客户端。
但是,RabbitMQ官方提供的Java客户端编码相对复杂,一样平常生产环境下我们更多会结合Spring来利用。而Spring的官方刚好基于RabbitMQ提供了这样一套消息收发的模板工具:SpringAMQP。并且还基于SpringBoot对其实现了主动装配,利用起来非常方便。
SpringAmqp的官方地址:
Spring AMQP
SpringAMQP提供了三个功能:
   
  
快速入门

   别忘了在我们的项目中,引入spring amqp的依赖。
  1. <dependencies>
  2.   <dependency>
  3.     <groupId>org.projectlombok</groupId>
  4.     <artifactId>lombok</artifactId>
  5.   </dependency>
  6.   <!--AMQP依赖,包含RabbitMQ-->
  7.   <dependency>
  8.     <groupId>org.springframework.boot</groupId>
  9.     <artifactId>spring-boot-starter-amqp</artifactId>
  10.   </dependency>
  11.   <!--单元测试-->
  12.   <dependency>
  13.     <groupId>org.springframework.boot</groupId>
  14.     <artifactId>spring-boot-starter-test</artifactId>
  15.   </dependency>
  16. </dependencies>
复制代码

在之前的案例中,我们都是颠末互换机发送消息到队列,不过有时候为了测试方便,我们也可以直接向队列发送消息,跳过互换机。
在入门案例中,我们就演示这样的简朴模型,如图:



也就是
   
  注意:这种模式一样平常测试利用,很少在生产中利用。

为了方便测试,我们在rabbitMQ控制台,创建名为 simple.queue 的队列。


添加队列后检察


接下来,我们就可以利用Java代码收发消息了。

消息发送

   在我们的项目application.yml 中 添加关于rabbitmq的设置信息。
  
  1. spring:
  2.   rabbitmq:
  3.     host: 123.56.247.70 # 你的虚拟机IP
  4.     port: 5672          # rabbitMQ端口
  5.     virtual-host: /sde  # 虚拟机名称
  6.     username: sundaoen  # 用户名
  7.     password: 8888888888       # 密码
复制代码



编写测试类

   在我们项目的publisher中创建测试类,并且利用 RabbitTemplate 发送消息。
  


  1. @SpringBootTest
  2. public class TestSendMessage {
  3.     @Autowired
  4.     private RabbitTemplate rabbitTemplate;
  5.     @Test
  6.     public void  testSimpleQueue(){
  7.         // 1 队列名称
  8.         String queueName = "simple.queue";
  9.         // 2 消息
  10.         String message = "hello simple.queue";
  11.         // 3 发送消息
  12.         rabbitTemplate.convertAndSend(queueName,message);
  13.     }
  14. }
复制代码

打开控制台,可以看到消息已经发送到队列中:


看看消息内容


接下来,我们再来实现消息接收。

消息接收

   同样的道理,也是先设置MQ地址。在application.yml 中
  1. spring:
  2.   rabbitmq:
  3.     host: 123.56.247.70 # 你的虚拟机IP
  4.     port: 5672          # rabbitMQ端口
  5.     virtual-host: /sde  # 虚拟机名称
  6.     username: sundaoen  # 用户名
  7.     password: 8888888888       # 密码
复制代码
在consumer服务中编写监听器类,并利用@RabbitListener实现消息的接收。
  1. @Slf4j
  2. @Component
  3. public class SimpleQueueListener {
  4.         /*
  5.         利用@RabbitListener注解,可以监听到对应队列的消息
  6.         一旦监听的队列有消息,就会回调当前方法,在方法中接收消息并消费处理消息
  7.          */
  8.     @RabbitListener(queues = "simple.queue")
  9.     public void listenerSimpleQueue(String msg){
  10.         System.out.println("SpringRabbitListener 监听到 simple.queue 队列中的消息是:" + msg);
  11.     }
  12. }
复制代码




WorkQueue模型

Work queues,任务模型。简朴来说就是让多个消费者绑定到一个队列,共同消费队列中的消息


当消息处理比力耗时的时候,大概生产消息的速度会远宏大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。
此时就可以利用work 模型,多个消费者共同处理消息处理,消息处理的速度就能大大提高了。
接下来,我们就来模拟这样的场景。
首先,我们在控制台创建一个新的队列,命名为work.queue:


添加后的结果


消息发送

这次我们循环发送,模拟大量消息堆积现象。
在publisher服务中的WorkQueueSendTest类中添加一个测试方法:


  1. @SpringBootTest
  2. public class WorkQueueSendTest {
  3.     @Autowired
  4.     private RabbitTemplate rabbitTemplate;
  5.     @Test
  6.     public void testSendWorkQueue() throws InterruptedException {
  7.         // 1 队列名称
  8.         String queueName = "work.queue";
  9.         // 2 消息
  10.         String message = "hello work.queue-";
  11.         // 3 发送消息
  12.         for (int i = 1; i <= 50; i++) {
  13.             // 每隔20毫秒发送一条消息,相当于一秒发送50条消息。
  14.             rabbitTemplate.convertAndSend(queueName,message + i);
  15.             Thread.sleep(20);
  16.         }
  17.     }
  18. }
复制代码
可以看到在work.queue 队列中有50条消息。



消息接收

要模拟多个消费者绑定同一个队列,我们在consumer服务中的,listener包中。新增WorkQueueListener类并添加2个新的方法:


  1. @Slf4j
  2. @Component
  3. public class WorkQueueListener {
  4.     /*
  5.     实现两个消费 work.queue的监听消费消息的方法;
  6.     一个方法消费后沉睡 20毫秒;一个消息消费后沉睡200毫秒;
  7.      */
  8.     @RabbitListener(queues = "work.queue")
  9.     public void listenerWorkQueue1(String msg){
  10.         System.out.println("消费者1接收到消息" + msg +" 时间:"+ LocalDateTime.now());
  11.         try {
  12.             Thread.sleep(20); // 沉睡20毫秒 1秒是1000毫秒等于1秒处理50条消息
  13.         } catch (InterruptedException e) {
  14.             e.printStackTrace();
  15.         }
  16.     }
  17.     @RabbitListener(queues = "work.queue")
  18.     public void listenerWorkQueue2(String msg){
  19.         System.out.println("***消费者2接收到消息" + msg +" 时间:"+ LocalDateTime.now());
  20.         try {
  21.             Thread.sleep(200); // 沉睡200毫秒 1秒是1000毫秒等于1秒处理5条消息
  22.         } catch (InterruptedException e) {
  23.             e.printStackTrace();
  24.         }
  25.     }
  26. }
复制代码
注意到这两消费者,都设置了Thead.sleep,模拟任务耗时:

测试看结果

  1. 消费者1接收到消息hello work.queue-1 时间:2025-02-05T14:53:00.928905400
  2. ***消费者2接收到消息hello work.queue-2 时间:2025-02-05T14:53:00.947629900
  3. 消费者1接收到消息hello work.queue-3 时间:2025-02-05T14:53:00.977764800
  4. 消费者1接收到消息hello work.queue-5 时间:2025-02-05T14:53:01.039608
  5. 消费者1接收到消息hello work.queue-7 时间:2025-02-05T14:53:01.101242200
  6. 消费者1接收到消息hello work.queue-9 时间:2025-02-05T14:53:01.160396600
  7. ***消费者2接收到消息hello work.queue-4 时间:2025-02-05T14:53:01.161396900
  8. 消费者1接收到消息hello work.queue-11 时间:2025-02-05T14:53:01.231704200
  9. 消费者1接收到消息hello work.queue-13 时间:2025-02-05T14:53:01.281879300
  10. 消费者1接收到消息hello work.queue-15 时间:2025-02-05T14:53:01.347333400
  11. ***消费者2接收到消息hello work.queue-6 时间:2025-02-05T14:53:01.376528100
  12. 消费者1接收到消息hello work.queue-17 时间:2025-02-05T14:53:01.407569700
  13. 消费者1接收到消息hello work.queue-19 时间:2025-02-05T14:53:01.464497900
  14. 消费者1接收到消息hello work.queue-21 时间:2025-02-05T14:53:01.525121200
  15. 消费者1接收到消息hello work.queue-23 时间:2025-02-05T14:53:01.587589500
  16. ***消费者2接收到消息hello work.queue-8 时间:2025-02-05T14:53:01.589591300
  17. 消费者1接收到消息hello work.queue-25 时间:2025-02-05T14:53:01.647549500
  18. 消费者1接收到消息hello work.queue-27 时间:2025-02-05T14:53:01.709757900
  19. 消费者1接收到消息hello work.queue-29 时间:2025-02-05T14:53:01.768879300
  20. ***消费者2接收到消息hello work.queue-10 时间:2025-02-05T14:53:01.801437800
  21. 消费者1接收到消息hello work.queue-31 时间:2025-02-05T14:53:01.829539900
  22. 消费者1接收到消息hello work.queue-33 时间:2025-02-05T14:53:01.895907400
  23. 消费者1接收到消息hello work.queue-35 时间:2025-02-05T14:53:01.950810
  24. 消费者1接收到消息hello work.queue-37 时间:2025-02-05T14:53:02.011575
  25. ***消费者2接收到消息hello work.queue-12 时间:2025-02-05T14:53:02.014526300
  26. 消费者1接收到消息hello work.queue-39 时间:2025-02-05T14:53:02.073814400
  27. 消费者1接收到消息hello work.queue-41 时间:2025-02-05T14:53:02.142812400
  28. 消费者1接收到消息hello work.queue-43 时间:2025-02-05T14:53:02.199522100
  29. ***消费者2接收到消息hello work.queue-14 时间:2025-02-05T14:53:02.228114600
  30. 消费者1接收到消息hello work.queue-45 时间:2025-02-05T14:53:02.255591100
  31. 消费者1接收到消息hello work.queue-47 时间:2025-02-05T14:53:02.315954800
  32. 消费者1接收到消息hello work.queue-49 时间:2025-02-05T14:53:02.377632900
  33. ***消费者2接收到消息hello work.queue-16 时间:2025-02-05T14:53:02.440855300
  34. ***消费者2接收到消息hello work.queue-18 时间:2025-02-05T14:53:02.654015100
  35. ***消费者2接收到消息hello work.queue-20 时间:2025-02-05T14:53:02.867783300
  36. ***消费者2接收到消息hello work.queue-22 时间:2025-02-05T14:53:03.080905400
  37. ***消费者2接收到消息hello work.queue-24 时间:2025-02-05T14:53:03.296731200
  38. ***消费者2接收到消息hello work.queue-26 时间:2025-02-05T14:53:03.512099400
  39. ***消费者2接收到消息hello work.queue-28 时间:2025-02-05T14:53:03.725353500
  40. ***消费者2接收到消息hello work.queue-30 时间:2025-02-05T14:53:03.939706400
  41. ***消费者2接收到消息hello work.queue-32 时间:2025-02-05T14:53:04.152588100
  42. ***消费者2接收到消息hello work.queue-34 时间:2025-02-05T14:53:04.367337200
  43. ***消费者2接收到消息hello work.queue-36 时间:2025-02-05T14:53:04.581549200
  44. ***消费者2接收到消息hello work.queue-38 时间:2025-02-05T14:53:04.793774100
  45. ***消费者2接收到消息hello work.queue-40 时间:2025-02-05T14:53:05.006103400
  46. ***消费者2接收到消息hello work.queue-42 时间:2025-02-05T14:53:05.220121400
  47. ***消费者2接收到消息hello work.queue-44 时间:2025-02-05T14:53:05.433498300
  48. ***消费者2接收到消息hello work.queue-46 时间:2025-02-05T14:53:05.645486500
  49. ***消费者2接收到消息hello work.queue-48 时间:2025-02-05T14:53:05.856447600
  50. ***消费者2接收到消息hello work.queue-50 时间:2025-02-05T14:53:06.065771700
复制代码
可以看到消费者1和消费者2竟然每人消费了25条消息:

也就是说消息是平均分配给每个消费者,并没有考虑到消费者的处理本领。导致1个消费者空闲,另一个消费者忙的不可开交。没有充实利用每一个消费者的本领,最终消息处理的耗时远远超过了1秒。这样显然是有问题的。

能者多劳

更改一下我们的设置文件,就好了。更改的是consumer消费者服务 application.yml 设置文件。
  1. spring:
  2.   rabbitmq:
  3.     listener:
  4.       simple:
  5.         prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
复制代码


重启项目,再次测试看结果。
  1. 消费者1接收到消息hello work.queue-1 时间:2025-02-05T16:19:40.610672600
  2. ***消费者2接收到消息hello work.queue-2 时间:2025-02-05T16:19:40.635078900
  3. 消费者1接收到消息hello work.queue-3 时间:2025-02-05T16:19:40.668399800
  4. 消费者1接收到消息hello work.queue-4 时间:2025-02-05T16:19:40.733468200
  5. 消费者1接收到消息hello work.queue-5 时间:2025-02-05T16:19:40.789432700
  6. 消费者1接收到消息hello work.queue-6 时间:2025-02-05T16:19:40.849740
  7. ***消费者2接收到消息hello work.queue-7 时间:2025-02-05T16:19:40.865255600
  8. 消费者1接收到消息hello work.queue-8 时间:2025-02-05T16:19:40.915186600
  9. 消费者1接收到消息hello work.queue-9 时间:2025-02-05T16:19:40.975302
  10. 消费者1接收到消息hello work.queue-10 时间:2025-02-05T16:19:41.035238100
  11. 消费者1接收到消息hello work.queue-11 时间:2025-02-05T16:19:41.098149900
  12. ***消费者2接收到消息hello work.queue-12 时间:2025-02-05T16:19:41.110162300
  13. 消费者1接收到消息hello work.queue-13 时间:2025-02-05T16:19:41.158752
  14. 消费者1接收到消息hello work.queue-14 时间:2025-02-05T16:19:41.214050800
  15. 消费者1接收到消息hello work.queue-15 时间:2025-02-05T16:19:41.275456500
  16. 消费者1接收到消息hello work.queue-16 时间:2025-02-05T16:19:41.338280900
  17. ***消费者2接收到消息hello work.queue-17 时间:2025-02-05T16:19:41.354040400
  18. 消费者1接收到消息hello work.queue-18 时间:2025-02-05T16:19:41.397333900
  19. 消费者1接收到消息hello work.queue-19 时间:2025-02-05T16:19:41.459536100
  20. 消费者1接收到消息hello work.queue-20 时间:2025-02-05T16:19:41.522984800
  21. 消费者1接收到消息hello work.queue-21 时间:2025-02-05T16:19:41.589369900
  22. ***消费者2接收到消息hello work.queue-22 时间:2025-02-05T16:19:41.595472400
  23. 消费者1接收到消息hello work.queue-23 时间:2025-02-05T16:19:41.639076100
  24. 消费者1接收到消息hello work.queue-24 时间:2025-02-05T16:19:41.702762100
  25. 消费者1接收到消息hello work.queue-25 时间:2025-02-05T16:19:41.761438700
  26. 消费者1接收到消息hello work.queue-26 时间:2025-02-05T16:19:41.823348300
  27. ***消费者2接收到消息hello work.queue-27 时间:2025-02-05T16:19:41.836398700
  28. 消费者1接收到消息hello work.queue-28 时间:2025-02-05T16:19:41.894946600
  29. 消费者1接收到消息hello work.queue-29 时间:2025-02-05T16:19:41.962451900
  30. 消费者1接收到消息hello work.queue-30 时间:2025-02-05T16:19:42.020227900
  31. ***消费者2接收到消息hello work.queue-31 时间:2025-02-05T16:19:42.066749100
  32. 消费者1接收到消息hello work.queue-32 时间:2025-02-05T16:19:42.080599800
  33. 消费者1接收到消息hello work.queue-33 时间:2025-02-05T16:19:42.143280700
  34. 消费者1接收到消息hello work.queue-34 时间:2025-02-05T16:19:42.204272700
  35. 消费者1接收到消息hello work.queue-35 时间:2025-02-05T16:19:42.270407300
  36. ***消费者2接收到消息hello work.queue-36 时间:2025-02-05T16:19:42.309818400
  37. 消费者1接收到消息hello work.queue-37 时间:2025-02-05T16:19:42.332003100
  38. 消费者1接收到消息hello work.queue-38 时间:2025-02-05T16:19:42.391974600
  39. 消费者1接收到消息hello work.queue-39 时间:2025-02-05T16:19:42.454012300
  40. 消费者1接收到消息hello work.queue-40 时间:2025-02-05T16:19:42.509398500
  41. ***消费者2接收到消息hello work.queue-41 时间:2025-02-05T16:19:42.555230800
  42. 消费者1接收到消息hello work.queue-42 时间:2025-02-05T16:19:42.570220
  43. 消费者1接收到消息hello work.queue-43 时间:2025-02-05T16:19:42.629378200
  44. 消费者1接收到消息hello work.queue-44 时间:2025-02-05T16:19:42.690519600
  45. 消费者1接收到消息hello work.queue-45 时间:2025-02-05T16:19:42.756214500
  46. ***消费者2接收到消息hello work.queue-46 时间:2025-02-05T16:19:42.797371400
  47. 消费者1接收到消息hello work.queue-47 时间:2025-02-05T16:19:42.813034800
  48. 消费者1接收到消息hello work.queue-48 时间:2025-02-05T16:19:42.876228100
  49. 消费者1接收到消息hello work.queue-49 时间:2025-02-05T16:19:42.939391
  50. 消费者1接收到消息hello work.queue-50 时间:2025-02-05T16:19:42.998590500
复制代码

可以发现,由于消费者1处理速度较快,以是处理了更多的消息;消费者2处理速度较慢,只处理了7条消息。而最终总的实验耗时也在1秒左右,大大提升。
正所谓能者多劳,这样充实利用了每一个消费者的处理本领,可以有效避免消息积压问题。

总结

Work模型的利用:


互换机类型

在之前的两个测试案例中,都没有互换机Exchange,生产者直接发送消息到队列。而一旦引入互换机,消息发送的模式会有很大变革:


可以看到,在订阅模型中,多了一个exchange脚色,而且过程略有变革:
   
  Exchange(互换机)只负责转发消息,不具备存储消息的本领,因此假如没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!
互换机的类型有四种:
   
  文档中,我们讲解前面的三种互换机模式。

Fanout互换机

Fanout,英文翻译是扇出,我觉得在MQ中叫广播更符合。
在广播模式下,消息发送流程是这样的:



我们的操持是这样的:




声明互换机和队列

在控制台创建 fanout.queue1 和 fanout.queue2 两个队列。


然后在创建一个互换机


绑定两个队列到互换机



消息发送

在publisher服务的FanoutExchangeTest类中添加测试方法:
  1. @SpringBootTest
  2. public class FanoutExchangeTest {
  3.     @Autowired
  4.     private RabbitTemplate rabbitTemplate;
  5.     /*
  6.     测试 fanout exchange;
  7.     向 test.fanout 交换机发送消息,消息内容为 hello everyone!,会发送到所有绑定到该交换机的队列
  8.      */
  9.     @Test
  10.     public void testSendFanoutExchange(){
  11.         // 1 交换机名称
  12.         String exchangeName = "test.fanout";
  13.         // 2 消息
  14.         String msg = "hello everyone!";
  15.         // 3 发送消息
  16.         rabbitTemplate.convertAndSend(exchangeName,"",msg);
  17.     }
  18. }
复制代码
注意:上述的 convertAndSend 方法的第2个参数:路由key 因为没有绑定,以是可以指定为空

看看rabbitMQ的控制台



消息接收

在consumer服务中添加FanoutQueueListener类,并新增两个方法,监听队列中的消息 作为消费者。
  1. @Slf4j
  2. @Component
  3. public class FanoutQueueListener {
  4.     /**
  5.      * 监听fanout.queue1队列
  6.      */
  7.     @RabbitListener(queues = "fanout.queue1")
  8.     public void listenFanoutQueue1(String msg){
  9.         System.out.println("【消费者1】 接收到消息:" + msg);
  10.     }
  11.     /**
  12.      * 监听fanout.queue2队列
  13.      */
  14.     @RabbitListener(queues = "fanout.queue2")
  15.     public void listenFanoutQueue2(String msg){
  16.         System.out.println("【消费者2】 接收到消息:" + msg);
  17.     }
  18. }
复制代码




总结

互换机的作用是什么?


Direct互换机

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


在Direct模型下:

案例需求如图



声明队列和互换机

首先在控制台声明两个队列direct.queue1和direct.queue2,这里不再展示过程:


然后声明一个direct类型的互换机,命名为test.direct:



然后利用red和blue作为key,绑定direct.queue1到test.direct:




绑定diretc.queue2




看看末了的绑定关系



消息发送

在publish服务中,新增 DirectExchangeTest 类发送消息。
  1. @SpringBootTest
  2. public class DirectExchangeTest {
  3.     @Autowired
  4.     private RabbitTemplate rabbitTemplate;
  5.     /*
  6.     测试 direct exchange;
  7.     向 test.direct 交换机发送消息,会根据路由key发送到所有绑定到该交换机的队列
  8.      */
  9.     @Test
  10.     public void testSendDirectExchange(){
  11.         // 1 交换机
  12.         String exchangeName = "test.direct";
  13.         // 2 消息
  14.         String msg = "这是一条消息,并且路由key是red 红色。";
  15.         // 3 发送消息 路由key为red
  16.         rabbitTemplate.convertAndSend(exchangeName,"red",msg);
  17.         //改变下消息
  18.         msg = "这是一条消息,并且路由key是blue 蓝色。";
  19.         rabbitTemplate.convertAndSend(exchangeName,"blue",msg);
  20.     }
  21. }
复制代码
看看rabbitMQ控制台,检察消息是否成功发送。



消息接收

在consumer服务中,添加 DirectQueueListener 类,并在里面编写两个方法。
  1. @Slf4j
  2. @Component
  3. public class DirectQueueListener {
  4.     /**
  5.      * 监听direct.queue1队列
  6.      */
  7.     @RabbitListener(queues = "direct.queue1")
  8.     public void listenDirectQueue1(String msg){
  9.         log.info("【消费者1】接收到消息:{}",msg);
  10.     }
  11.     /**
  12.      * 监听direct.queue2队列
  13.      * @param msg
  14.      */
  15.     @RabbitListener(queues = "direct.queue2")
  16.     public void listenDirectQueue2(String msg){
  17.         log.info("【消费者2】接收到消息:{}",msg);
  18.     }
  19. }
复制代码


由于 test.redirect 互换机绑定的两个队列的路由key有red;以是指定了路由key为red的消息能被两个消费者都收到。
而路由key为 blue 的队列只有direct.queue1;以是只有监听这个队列的 消费者1 可以或许接收到消息:

总结

形貌下Direct互换机与Fanout互换机的差异?


Topic互换机

Topic类型互换机

Topic类型的Exchange与Direct相比,都是可以根据RoutingKey把消息路由到不同的队列。
只不过Topic类型Exchange可以让队列在绑定RoutingKey 的时候利用通配符!
RoutingKey 一样平常都是有一个或多个单词构成,多个单词之间以.分割,例如: item.insert
通配符规则:

举例:

图示:


假如此时publisher发送的消息利用的RoutingKey共有四种:

解释:




接下来,我们就按照上图所示,来演示一下Topic互换机的用法。
首先,在控制台按照图示例子创建队列、互换机,并利用通配符绑定队列和互换机。此处步调略。最终结果如下:

创建互换机和队列




创建test.topic 互换机


看看结果


给test.topic 互换机绑定两个队列





消息发送

在consumer服务中,新增 TopicExchangeTest类 发送消息。

  1. @SpringBootTest
  2. public class TopicExchangeTest {
  3.     @Autowired
  4.     private RabbitTemplate rabbitTemplate;
  5.     @Test
  6.     public void testSendTopicExchange(){
  7.         // 1 交换机
  8.         String exchangeName = "test.topic";
  9.         // 2 消息
  10.         String msg = "我是TopicExchange交换机的消息,路由key是 china.news";
  11.         // 3 发送路由key为 china.news 的消息
  12.         rabbitTemplate.convertAndSend(exchangeName,"china.news",msg);
  13.     }
  14. }
复制代码



消息接收

在consumer服务中,添加 TopicExchangeListener 类,编写两个方法监听消息。
  1. @Slf4j
  2. @Component
  3. public class TopicExchangeListener {
  4.     /**
  5.      * 监听topic.queue1队列
  6.      */
  7.     @RabbitListener(queues = "topic.queue1")
  8.     public void listenTopicQueue1(String msg) {
  9.         log.info("【消费者1】监听到消息:{}", msg);
  10.     }
  11.     /**
  12.      * 监听topic.queue2队列
  13.      */
  14.     @RabbitListener(queues ="topic.queue2")
  15.     public void listenTopicQueue2(String msg) {
  16.         log.info("【消费者2】监听到消息:{}", msg);
  17.     }
  18. }
复制代码



总结

形貌下Direct互换机与Topic互换机的差异?


代码声明互换机和队列

在之前我们都是基于RabbitMQ控制台来创建队列、互换机。但是在实际开发时,队列和互换机是程序员界说的,未来项目上线,又要交给运维去创建。那么程序员就须要把程序中运行的所有队列和互换机都写下来,交给运维。在这个过程中是很容易出现错误的。
因此保举的做法是由程序启动时查抄队列和互换机是否存在,假如不存在主动创建。

根本API

SpringAMQP提供了一个Queue类,用来创建队列:


SpringAMQP还提供了一个Exchange接口,来表现所有不同类型的互换机:


我们可以自己创建队列和互换机,不过SpringAMQP还提供了ExchangeBuilder来简化这个过程:


而在绑定队列和互换机时,则须要利用BindingBuilder来创建Binding对象:



把之前创建的队列和互换机删除

删除后的队列


删除后的互换机


Ideal控制台报错



这是因为我们的队列和互换机都删除了,里面写的 RabbitListener 还在监听队列中的消息,但是队列没有了,以是报错。
fanout示例

   在consumer服务中,新建config包。并创建FanoutConfig 类 在里面编写代码,创建test.fanout 互换机和fanout.queue1 和fanout.queue2 队列。 并启动consumer服务
  1. @Configuration
  2. public class FanoutConfig {
  3.     // 声明 Fanout 类型的交换机
  4.     @Bean
  5.     public FanoutExchange fanoutExchange(){
  6.         return new FanoutExchange("test.fanout");
  7.     }
  8.     //声明队列,名称为 fanout.queue1
  9.     @Bean
  10.     public Queue fanoutQueue1(){
  11.         return new Queue("fanout.queue1");
  12.     }
  13.     //绑定队列和交换机
  14.     @Bean
  15.     public Binding fanoutBinding1(FanoutExchange fanoutExchange,Queue fanoutQueue1){
  16.         return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
  17.     }
  18.     //声明队列,名称为 fanout.queue2
  19.     @Bean
  20.     public Queue fanoutQueue2(){
  21.         return new Queue("fanout.queue2");
  22.     }
  23.     //绑定队列和交换机
  24.     @Bean
  25.     public Binding fanoutBinding2(FanoutExchange fanoutExchange,Queue fanoutQueue2){
  26.         return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
  27.     }
  28. }
复制代码
看看rbbitMQ控制台结果


看看互换机



Direct示例

   在consumer 服务中的 config包中,新建 DirectConfig 类,编写代码创建互换机和队列。direct模式由于要绑定多个key,会比力贫苦一点,因为每一个key都要写一个binding方法。
  1. @Configuration
  2. public class DirectConfig {
  3.     //声明 test.direct 交换机
  4.     @Bean
  5.     public DirectExchange directExchange(){
  6.         return new DirectExchange("test.direct");
  7.     }
  8.     //声明 direct.queue1 队列
  9.     @Bean
  10.     public Queue directQueue1(){
  11.         return new Queue("direct.queue1");
  12.     }
  13.     //绑定 direct.queue1 队列到 test.direct 交换机上 路由key是 red
  14.     @Bean
  15.     public Binding directBindingQueue1Red(DirectExchange directExchange,Queue directQueue1){
  16.         return BindingBuilder.bind(directQueue1).to(directExchange).with("red");
  17.     }
  18.     //绑定 direct.queue1 队列到 test.direct 交换机上 路由key是 blue
  19.     @Bean
  20.     public Binding directBindingQueue1Blue(DirectExchange directExchange,Queue directQueue1){
  21.         return BindingBuilder.bind(directQueue1).to(directExchange).with("blue");
  22.     }
  23.     //声明 direct.queue2 队列
  24.     @Bean
  25.     public Queue directQueue2(){
  26.         return new Queue("direct.queue2");
  27.     }
  28.     //绑定 direct.queue2 队列到 test.direct 交换机上 路由key是 red
  29.     @Bean
  30.     public Binding directBindingQueue2Red(DirectExchange directExchange, Queue directQueue2){
  31.         return BindingBuilder.bind(directQueue2).to(directExchange).with("red");
  32.     }
  33.     //绑定 direct.queue2 队列到 test.direct 交换机上 路由key是 yellow
  34.     @Bean
  35.     public Binding directBindingQueue2Yellow(DirectExchange directExchange,Queue directQueue2){
  36.         return BindingBuilder.bind(directQueue2).to(directExchange).with("yellow");
  37.     }
  38.    
  39. }
复制代码
看看rabbitMQ控制台


看看互换机和绑定关系





Topic示例

   在consumer 服务中的config包里面,新创建TopicConfig类,编写代码创建互换机和队列。
  1. @Configuration
  2. public class TopicConfig {
  3.     //声明 test.topic 交换机
  4.     @Bean
  5.     public TopicExchange topicExchange(){
  6.         return new TopicExchange("test.topic");
  7.     }
  8.     //声明 topic.queue1 队列
  9.     @Bean
  10.     public Queue topicQueue1(){
  11.         return new Queue("topic.queue1");
  12.     }
  13.     //绑定队列和交换机 路由key是 china.#
  14.     @Bean
  15.     public Binding topicBinding1(TopicExchange topicExchange,Queue topicQueue1){
  16.         return BindingBuilder.bind(topicQueue1).to(topicExchange).with("china.#");
  17.     }
  18.     //声明 topic.queue2 队列
  19.     @Bean
  20.     public Queue topicQueue2(){
  21.         return new Queue("topic.queue2");
  22.     }
  23.     //绑定队列和交换机 路由key是 #.news
  24.     @Bean
  25.     public Binding topicBinding2(TopicExchange topicExchange,Queue topicQueue2){
  26.         return BindingBuilder.bind(topicQueue2).to(topicExchange).with("#.news");
  27.     }
  28. }
复制代码
看看控制台结果


互换机





基于注解声明

基于@Bean的方式声明队列和互换机比力贫苦,Spring还提供了基于注解方式来声明。不过是在消息监听的时候基于注解的方式来声明。
例如,我们同样声明Direct模式的互换机和队列;用注解的方式声明下。
   先把之前创建的 互换机和队列删除。
  删除后的结果




Fanout示例

  1. @Configuration
  2. public class FanoutRabbitListener {
  3.     // 监听fanout.queue1 队列的消息
  4.     @RabbitListener(bindings = @QueueBinding(
  5.             value = @Queue("fanout.queue1"),
  6.             exchange = @Exchange(value = "test.fanout",type = ExchangeTypes.FANOUT),
  7.             key = ""
  8.     ))
  9.     public void listenFanoutQueue1(String msg){
  10.         System.out.println("【消费者1】 监听到消息" + msg);
  11.     }
  12.     // 监听fanout.queue2 队列的消息
  13.     @RabbitListener(bindings = @QueueBinding(
  14.             value = @Queue("fanout.queue2"),
  15.             exchange = @Exchange(value = "test.fanout",type = ExchangeTypes.FANOUT),
  16.             key = ""
  17.     ))
  18.     public void listenFanoutQueue2(String msg){
  19.         System.out.println("【消费者2】 监听到消息" + msg);
  20.     }
  21. }
复制代码
启动consumer服务看结果


互换机和绑定关系





Direct示例

   新建 DirectRabbitListener 类,并在里面编写代码进行测试。
  1. @Configuration
  2. public class DirectRabbitListener {
  3.     // 声明 direct.queue1
  4.     @RabbitListener(bindings = @QueueBinding(
  5.             value = @Queue("direct.queue1"),
  6.             exchange = @Exchange(value = "test.direct",type = ExchangeTypes.DIRECT),
  7.             key = {"red","blue"}
  8.     ))
  9.     public void listenDirectQueue1(String msg){
  10.         System.out.println("【消费者1】 接收到消息:" + msg);
  11.     }
  12.     // 声明direct.queue2
  13.     @RabbitListener(bindings =@QueueBinding(
  14.             value = @Queue("direct.queue2"),
  15.             exchange = @Exchange(value = "test.direct",type = ExchangeTypes.DIRECT),
  16.             key = {"red","yellow"}
  17.     ))
  18.     public void listenDirectQueue2(String msg){
  19.         System.out.println("【消费者2】 接收到消息:" + msg);
  20.     }
  21. }
复制代码
看看结果


互换机和绑定关系





Topic示例

在consumer服务中的 config包里面,创建TopicRabbitListener类。编写代码进行测试

  1. @Configuration
  2. public class TopicRabbitListener {
  3.     //声明topic.queue1 队列
  4.     @RabbitListener(bindings = @QueueBinding(
  5.             value = @Queue("topic.queue1"),
  6.             exchange = @Exchange(value = "test.topic",type = ExchangeTypes.TOPIC),
  7.             key = {"china.#"}
  8.     ))
  9.     public void listenTopicQueue1(String msg){
  10.         System.out.println("【消费者1】接收到消息:"+msg);
  11.     }
  12.     //声明 topic.queue2 队列
  13.     @RabbitListener(bindings = @QueueBinding(
  14.             value = @Queue("topic.queue2"),
  15.             exchange = @Exchange(value = "test.topic",type = ExchangeTypes.TOPIC),
  16.             key = {"#.news"}
  17.     ))
  18.     public void listenTopicQueue2(String msg){
  19.         System.out.println("【消费者2】接收到消息:"+msg);
  20.     }
  21. }
复制代码
看看结果


互换机和绑定关系






免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4