2、RabbitMQ之SpringAMQP

1、什么是SpringAMQP

SpringAMQP是基于RabbitMQ封装的一套模板,并且还利用SpringBoot对其实现了自动装配,使用起来非常方便。

SpringAmqp的官方地址:https://spring.io/projects/spring-amqp

2、简单队列模型

1、在父工程pom.xml中引入依赖

xml
复制代码
<!--AMQP依赖,包含RabbitMQ--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>

2、首先在生产者端配置MQ地址,在application.yml中添加配置:

1
yml
复制代码
spring: rabbitmq: host: 192.168.58.131 #rabbitMQ的ip地址 port: 5672 #端口 username: jie #用户名 password: 1234 #密码 virtual-host: / #虚拟主机

2、在生产者端编写测试类SpringAmqpTest,并利用RabbitTemplate实现消息发送:

java
复制代码
package com.jie.mq.helloworld.spring; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest public class SpringAmqpTest { @Autowired private RabbitTemplate rabbitTemplate; @Test public void test() { //队列名称 String queueName = "simple.queue"; //消息 String message = "hello, spring amqp!"; //发送消息 rabbitTemplate.convertAndSend(queueName, message); } }

点击运行后可以到浏览器看看。

2

3、在消费者端配置MQ地址,在application.yml中添加配置(和在生产者端一致)

4、然后在生产者服务新建一个类,代码如下:

java
复制代码
package com.jie.mq.listener; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class SpringRabbitListener { @RabbitListener(queues = "simple.queue") public void listenSimpleQueue(String msg){ System.out.println("spring 消费者接收到消息 :【" + msg + "】"); } }

5、启动消费者,查看控制台和浏览器。

3 4

3、WorkQueue 工作队列

Work queues,也被称为(Task queues),任务模型。简单来说就是让多个消费者绑定到一个队列,共同消费队列中的消息

5

当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。

此时就可以使用work 模型,多个消费者共同处理消息处理,速度就能大大提高了。

3.1 模拟WorkQueue,实现一个队列绑定多个消费者

1、消息发送

这次我们循环发送,模拟大量消息堆积现象。

在生产者服务中添加一个测试方法:

java
复制代码
/** * @description:向队列中不停发送消息,模拟消息堆积。 * @author: jie * @time: 2022/2/22 9:23 */ @Test public void test2() throws InterruptedException { //队列名称 String queueName = "simple.queue"; //消息 String message = "hello, spring amqp!--"; for (int i = 1; i < 50; i++) { //发送消息 rabbitTemplate.convertAndSend(queueName, message+i); //休眠 Thread.sleep(20); } }

2、消息接收

要模拟多个消费者绑定同一个队列,我们在消费者服务的中添加2个新的方法:

java
复制代码
@RabbitListener(queues = "simple.queue") public void listenWorkQueue1(String msg) throws InterruptedException { System.out.println("spring 消费者1接收到消息 :【" + msg + "】"+ LocalTime.now()); //休眠 Thread.sleep(20); } @RabbitListener(queues = "simple.queue") public void listenWorkQueue2(String msg) throws InterruptedException { System.err.println("消费者2........接收到消息:【" + msg + "】" + LocalTime.now()); //休眠 Thread.sleep(200); }

3、测试

启动消费者后,在执行生产者服务中刚刚编写的发送测试方法InterruptedException。

可以看到消费者1很快完成了自己的25条消息。消费者2却在缓慢的处理自己的25条消息。

6

也就是说消息是平均分配给每个消费者,并没有考虑到消费者的处理能力。这样显然是有问题的。

4、能者多劳

在spring中有一个简单的配置,可以解决这个问题。我们修改消费者服务的application.yml文件,添加配置:

7

重启消费者,再重新发送消息。

8

5、小结

Work模型的使用:

  • 多个消费者绑定到一个队列,同一条消息只会被一个消费者处理
  • 通过设置prefetch来控制消费者预取的消息数量

4、发布/订阅

发布订阅模式与之前案例的区别就是允许将同一消息发送给多个消费者。实现方式是加入了exchange(交换机)。

发布订阅的模型如图:

9

可以看到,在订阅模型中,多了一个exchange角色,而且过程略有变化:

  • Publisher:生产者,也就是要发送消息的程序,但是不再发送到队列中,而是发给exchange(交换机)
  • Exchange:交换机。一方面,接收生产者发送的消息。另一方面,知道如何处理消息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作,取决于Exchange的类型。Exchange有以下3种类型:
    • Fanout:广播,将消息交给所有绑定到交换机的队列
    • Direct:路由,把消息交给符合指定routing key 的队列
    • Topic:通配符,把消息交给符合routing pattern(路由模式) 的队列
  • Consumer:消费者,与以前一样,订阅队列,没有变化
  • Queue:消息队列也与以前一样,接收消息、缓存消息。

Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!

4.1 Fanout(广播)

Fanout,英文翻译是扇出,在MQ中叫广播更合适。

11、5

在广播模式下,消息发送流程是这样的:

  1. 可以有多个队列。
  2. 每个队列都要绑定到Exchange(交换机)。
  3. 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。
  4. 交换机把消息发送给绑定过的所有队列。
  5. 订阅队列的消费者都能拿到消息。

1、在消费者中创建一个配置类,声明队列和交换机:

java
复制代码
package com.jie.mq.config; 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; /** * @description:广播交换机配置类 * @author: jie * @time: 2022/2/22 11:09 */ @Configuration public class FanoutConfig { /** * @description:创建交换机itcast.fanout * @author: jie * @time: 2022/2/12 19:38 */ @Bean public FanoutExchange fanoutExchange(){ return new FanoutExchange("itcast.fanout"); } /** * @description:创建队列fanout.queuel * @author: jie * @time: 2022/2/12 19:40 */ @Bean public Queue fanoutQueue1(){ return new Queue("fanout.queuel"); } /** * @description:绑定队列fanout.queuel到交换机 * @author: jie * @time: 2022/2/12 19:41 */ @Bean public Binding fanoutBinding1(Queue fanoutQueue1,FanoutExchange fanoutExchange){ return BindingBuilder .bind(fanoutQueue1) .to(fanoutExchange); } // fanout.queue2 /** * @description:创建队列fanout.queue2 * @author: jie * @time: 2022/2/12 19:40 */ @Bean public Queue fanoutQueue2(){ return new Queue("fanout.queue2"); } /** * @description:绑定队列fanout.queue2到交换机 * @author: jie * @time: 2022/2/12 19:41 */ @Bean public Binding fanoutBinding2(Queue fanoutQueue2,FanoutExchange fanoutExchange){ return BindingBuilder .bind(fanoutQueue2) .to(fanoutExchange); } }

运行消费者然后查看浏览器。

10

2、消息发送

在生产者服务的测试类中添加测试方法:

java
复制代码
/** * @description:测试交换机发送消息 * @author: jie * @time: 2022/2/22 11:18 */ @Test public void testFanoutExchange() { //交换机名称 String exchangeName = "itcast.fanout"; //消息 String message = "hello,every one!"; // 发送消息 rabbitTemplate.convertAndSend(exchangeName,"",message); }

3、消息接收

在消费者服务中添加两个方法,作为消费者:

java
复制代码
@RabbitListener(queues = "fanout.queuel") public void listenFanoutQueue1(String msg){ System.out.println("消费者接收到fanout.queuel的消息 :【" + msg + "】"); } @RabbitListener(queues = "fanout.queue2") public void listenFanoutQueue2(String msg){ System.out.println("消费者接收到fanout.queue2的消息 :【" + msg + "】"); }

4、测试

运行生产者消息发送,启动消费者,查看控制台。

11

5、小结

交换机的作用是什么?

  • 接收生产者发送的消息
  • 将消息按照规则路由到与之绑定的队列
  • 不能缓存消息,路由失败,消息丢失
  • FanoutExchange的会将消息路由到每个绑定的队列

声明队列、交换机、绑定关系的Bean是什么?

  • Queue(队列)
  • FanoutExchange(广播交换机)
  • Binding(绑定)

4.2、Direct(路由)

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

Direct Exchange 会将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes)。

12

在Direct模型下:

  • 队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)
  • 消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey
  • Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行判断,只有队列的Routingkey与消息的 Routing key完全一致,才会接收到消息

1、消息接收

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

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

java
复制代码
@RabbitListener(bindings = @QueueBinding( //队列 value = @Queue(name = "driect.queue1"), //交换机 exchange = @Exchange(name = "itcast.direct",type = ExchangeTypes.DIRECT), key = {"red","blue"} )) public void listenDirectQueue2(String msg){ System.out.println("消费者接收到direct.queue1的消息 :【" + msg + "】"); } @RabbitListener(bindings = @QueueBinding( //队列 value = @Queue(name = "driect.queue2"), //交换机 exchange = @Exchange(name = "itcast.direct",type = ExchangeTypes.DIRECT), key = {"red","yellow"} )) public void listenDirectQueue1(String msg){ System.out.println("消费者接收到direct.queue2的消息 :【" + msg + "】"); }
13

2、消息发送

java
复制代码
@Test public void testSendDirectExchange(){ //交换机名称 String exchangeName = "itcast.direct"; //消息 String message = "hello,jie"; // 发送消息 rabbitTemplate.convertAndSend(exchangeName,"blue",message); }
14

3、总结

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

  • Fanout交换机将消息路由给每一个与之绑定的队列
  • Direct交换机根据RoutingKey判断路由给哪个队列
  • 如果多个队列具有相同的RoutingKey,则与Fanout功能类似

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

  • @Queue
  • @Exchange

4.3 Topic(通配符)

Topic类型的ExchangeDirect相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符!

Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert

通配符规则:

#:匹配一个或多个词

*:匹配不多不少恰好1个词

举例:

item.#:能够匹配item.spu.insert 或者 item.spu

item.*:只能匹配item.spu

1、消息发送

在生产者服务的中添加测试方法:

java
复制代码
@Test public void testSendTopicExchange(){ //交换机名称 String exchangeName = "itcast.topic"; //消息 String message = "2022冬奥运在中国开始了!"; // 发送消息 rabbitTemplate.convertAndSend(exchangeName,"china.weather",message); }

2、消息接收

在消费者服务中添加方法:

java
复制代码
@RabbitListener(bindings = @QueueBinding( value = @Queue(name = "topic.queue1"), exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC), key = "china.#" )) public void listenTopicQueue1(String msg){ System.out.println("消费者接收到topic.queue1的消息 :【" + msg + "】"); } @RabbitListener(bindings = @QueueBinding( value = @Queue(name = "topic.queue2"), exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC), key = "#.news" )) public void listenTopicQueue2(String msg){ System.out.println("消费者接收到topic.queue2的消息 :【" + msg + "】"); }
15

3、小结

  • Topic交换机接收的消息RoutingKey必须是多个单词,以 **.** 分割
  • Topic交换机与队列绑定时的bindingKey可以指定通配符
  • #:代表0个或多个词
  • *:代表1个词

5、消息转换器

Spring会把你发送的消息序列化为字节发送给MQ,接收消息的时候,还会把字节反序列化为Java对象。

默认情况下Spring采用的序列化方式是JDK序列化。众所周知,JDK序列化存在下列问题:

  • 数据体积过大
  • 有安全漏洞
  • 可读性差

我们来测试一下。

5.1 测试默认转换器

java
复制代码
@Test public void test6() { Map<String,Object> msg = new HashMap<>(); msg.put("name","zs"); msg.put("age",24); rabbitTemplate.convertAndSend("object.queue",msg); }

我们修改消息发送的代码,发送一个Map对象:

发送消息后查看浏览器:

16

5.2 配置JSON转换器

显然,JDK序列化方式并不合适。我们希望消息体的体积更小、可读性更高,因此可以使用JSON方式来做序列化和反序列化。

在生产者和消费者两个服务中都引入依赖:

xml
复制代码
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency>

配置消息转换器。

在启动类中添加一个Bean即可:

text
复制代码
@Bean public MessageConverter messageConverter(){ return new Jackson2JsonMessageConverter(); }
17

查看浏览器

18
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP