当前位置: 首页 > news >正文

SpringCloud 微服务全栈体系(十一)

第十章 RabbitMQ

三、SpringAMQP

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

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

在这里插入图片描述

在这里插入图片描述

  • SpringAMQP 提供了三个功能:

    • 自动声明队列、交换机及其绑定关系
    • 基于注解的监听器模式,异步接收消息
    • 封装了 RabbitTemplate 工具,用于发送消息

1. Basic Queue 简单队列模型

  • 在父工程 mq-demo 中引入依赖
<!--AMQP依赖,包含RabbitMQ-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
1.1 消息发送
  • 首先配置 MQ 地址,在 publisher 服务的 application.yml 中添加配置:
spring:rabbitmq:host: 192.168.150.101 # 主机名port: 5672 # 端口virtual-host: / # 虚拟主机username: alex # 用户名password: 123321 # 密码
  • 然后在 publisher 服务中编写测试类 SpringAmqpTest,并利用 RabbitTemplate 实现消息发送:
package com.alex.mq.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;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {@Autowiredprivate RabbitTemplate rabbitTemplate;@Testpublic void testSimpleQueue() {// 队列名称String queueName = "simple.queue";// 消息String message = "hello, spring amqp!";// 发送消息rabbitTemplate.convertAndSend(queueName, message);}
}
1.2 消息接收
  • 首先配置 MQ 地址,在 consumer 服务的 application.yml 中添加配置:
spring:rabbitmq:host: 192.168.150.101 # 主机名port: 5672 # 端口virtual-host: / # 虚拟主机username: alex # 用户名password: 123321 # 密码
  • 然后在 consumer 服务的com.alex.mq.listener包中新建一个类 SpringRabbitListener,代码如下:
package com.alex.mq.listener;import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
public class SpringRabbitListener {@RabbitListener(queues = "simple.queue")public void listenSimpleQueueMessage(String msg) throws InterruptedException {System.out.println("spring 消费者接收到消息:【" + msg + "】");}
}
1.3 测试
  • 启动 consumer 服务,然后在 publisher 服务中运行测试代码,发送 MQ 消息

2. Work Queue

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

在这里插入图片描述

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

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

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

  • 在 publisher 服务中的 SpringAmqpTest 类中添加一个测试方法:

/*** workQueue* 向队列中不停发送消息,模拟消息堆积。*/
@Test
public void testWorkQueue() throws InterruptedException {// 队列名称String queueName = "simple.queue";// 消息String message = "hello, message_";for (int i = 0; i < 50; i++) {// 发送消息rabbitTemplate.convertAndSend(queueName, message + i);Thread.sleep(20);}
}
2.2 消息接收
  • 要模拟多个消费者绑定同一个队列,我们在 consumer 服务的 SpringRabbitListener 中添加 2 个新的方法:
@RabbitListener(queues = "simple.queue")
public void listenWorkQueue1(String msg) throws InterruptedException {System.out.println("消费者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);
}
  • 注意到这个消费者 sleep 了 1000 秒,模拟任务耗时。
2.3 测试
  • 启动 ConsumerApplication 后,在执行 publisher 服务中刚刚编写的发送测试方法 testWorkQueue。

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

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

2.4 能者多劳
  • 在 spring 中有一个简单的配置,可以解决这个问题。我们修改 consumer 服务的 application.yml 文件,添加配置:
spring:rabbitmq:listener:simple:prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
2.5 总结
  • Work 模型的使用:

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

3. 发布/订阅

  • 发布订阅的模型如图:

在这里插入图片描述

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

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

4. Fanout

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

在这里插入图片描述

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

    • 可以有多个队列
    • 每个队列都要绑定到 Exchange(交换机)
    • 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定
    • 交换机把消息发送给绑定过的所有队列
    • 订阅队列的消费者都能拿到消息
  • 计划如下:

    • 创建一个交换机 alex.fanout,类型是 Fanout
    • 创建两个队列 fanout.queue1 和 fanout.queue2,绑定到交换机 alex.fanout

在这里插入图片描述

4.1 声明队列和交换机
  • Spring 提供了一个接口 Exchange,来表示所有不同类型的交换机:

在这里插入图片描述

  • 在 consumer 中创建一个类,声明队列和交换机:
package com.alex.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;@Configuration
public class FanoutConfig {/*** 声明交换机* @return Fanout类型交换机*/@Beanpublic FanoutExchange fanoutExchange(){return new FanoutExchange("alex.fanout");}/*** 第1个队列*/@Beanpublic Queue fanoutQueue1(){return new Queue("fanout.queue1");}/*** 绑定队列和交换机*/@Beanpublic Binding bindingQueue1(Queue fanoutQueue1, FanoutExchange fanoutExchange){return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);}/*** 第2个队列*/@Beanpublic Queue fanoutQueue2(){return new Queue("fanout.queue2");}/*** 绑定队列和交换机*/@Beanpublic Binding bindingQueue2(Queue fanoutQueue2, FanoutExchange fanoutExchange){return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);}
}
4.2 消息发送
  • 在 publisher 服务的 SpringAmqpTest 类中添加测试方法:
@Test
public void testFanoutExchange() {// 队列名称String exchangeName = "alex.fanout";// 消息String message = "hello, everyone!";rabbitTemplate.convertAndSend(exchangeName, "", message);
}
4.3 消息接收
  • 在 consumer 服务的 SpringRabbitListener 中添加两个方法,作为消费者:
@RabbitListener(queues = "fanout.queue1")
public void listenFanoutQueue1(String msg) {System.out.println("消费者1接收到Fanout消息:【" + msg + "】");
}@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String msg) {System.out.println("消费者2接收到Fanout消息:【" + msg + "】");
}
4.4 总结
  • 交换机的作用是什么?

    • 接收 publisher 发送的消息
    • 将消息按照规则路由到与之绑定的队列
    • 不能缓存消息,路由失败,消息丢失
    • FanoutExchange 的会将消息路由到每个绑定的队列
  • 声明队列、交换机、绑定关系的 Bean 是什么?

    • Queue
    • FanoutExchange
    • Binding

5. Direct

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

在这里插入图片描述

  • 在 Direct 模型下:

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

  1. 利用@RabbitListener 声明 Exchange、Queue、RoutingKey

  2. 在 consumer 服务中,编写两个消费者方法,分别监听 direct.queue1 和 direct.queue2

  3. 在 publisher 中编写测试方法,向 alex. direct 发送消息

在这里插入图片描述

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

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

@RabbitListener(bindings = @QueueBinding(value = @Queue(name = "direct.queue1"),exchange = @Exchange(name = "alex.direct", type = ExchangeTypes.DIRECT),key = {"red", "blue"}
))
public void listenDirectQueue1(String msg){System.out.println("消费者接收到direct.queue1的消息:【" + msg + "】");
}@RabbitListener(bindings = @QueueBinding(value = @Queue(name = "direct.queue2"),exchange = @Exchange(name = "alex.direct", type = ExchangeTypes.DIRECT),key = {"red", "yellow"}
))
public void listenDirectQueue2(String msg){System.out.println("消费者接收到direct.queue2的消息:【" + msg + "】");
}
5.2 消息发送
  • 在 publisher 服务的 SpringAmqpTest 类中添加测试方法:
@Test
public void testSendDirectExchange() {// 交换机名称String exchangeName = "alex.direct";// 消息String message = "红色警报!日本乱排核废水,导致海洋生物变异,惊现哥斯拉!";// 发送消息rabbitTemplate.convertAndSend(exchangeName, "red", message);
}
5.3 总结
  • 描述下 Direct 交换机与 Fanout 交换机的差异?

    • Fanout 交换机将消息路由给每一个与之绑定的队列
    • Direct 交换机根据 RoutingKey 判断路由给哪个队列
    • 如果多个队列具有相同的 RoutingKey,则与 Fanout 功能类似
  • 基于@RabbitListener 注解声明队列和交换机有哪些常见注解?

    • @Queue
    • @Exchange

6. Topic

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

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

  • 通配符规则:

    • #:匹配一个或多个词

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

  • 举例:

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

    • item.*:只能匹配item.spu

  • 图示:

在这里插入图片描述

  • 解释:

    • Queue1:绑定的是china.# ,因此凡是以 china.开头的routing key 都会被匹配到。包括 china.news 和 china.weather
    • Queue2:绑定的是#.news ,因此凡是以 .news结尾的 routing key 都会被匹配。包括 china.news 和 japan.news
  • 案例需求(实现思路如下):

  1. 利用@RabbitListener 声明 Exchange、Queue、RoutingKey

  2. 在 consumer 服务中,编写两个消费者方法,分别监听 topic.queue1 和 topic.queue2

  3. 在 publisher 中编写测试方法,向 alex.topic 发送消息

在这里插入图片描述

6.2 消息发送
  • 在 publisher 服务的 SpringAmqpTest 类中添加测试方法:
/*** topicExchange*/
@Test
public void testSendTopicExchange() {// 交换机名称String exchangeName = "alex.topic";// 消息String message = "喜报!孙悟空大战哥斯拉,胜!";// 发送消息rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
}
6.3 消息接收
  • 在 consumer 服务的 SpringRabbitListener 中添加方法:
@RabbitListener(bindings = @QueueBinding(value = @Queue(name = "topic.queue1"),exchange = @Exchange(name = "alex.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 = "alex.topic", type = ExchangeTypes.TOPIC),key = "#.news"
))
public void listenTopicQueue2(String msg){System.out.println("消费者接收到topic.queue2的消息:【" + msg + "】");
}
6.4 总结
  • 描述下 Direct 交换机与 Topic 交换机的差异?

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

7. 消息转换器

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

在这里插入图片描述

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

    • 数据体积过大
    • 有安全漏洞
    • 可读性差
  • 测试一下。

7.1 测试默认转换器
  • 修改消息发送的代码,发送一个 Map 对象:
@Test
public void testSendMap() throws InterruptedException {// 准备消息Map<String,Object> msg = new HashMap<>();msg.put("name", "Jack");msg.put("age", 21);// 发送消息rabbitTemplate.convertAndSend("simple.queue", "", msg);
}
  • 停止 consumer 服务
  • 发送消息后查看控制台:

在这里插入图片描述

7.2 配置 JSON 转换器
  • 显然,JDK 序列化方式并不合适。我们希望消息体的体积更小、可读性更高,因此可以使用 JSON 方式来做序列化和反序列化。
  • 在 publisher 和 consumer 两个服务中都引入依赖:
<dependency><groupId>com.fasterxml.jackson.dataformat</groupId><artifactId>jackson-dataformat-xml</artifactId><version>2.9.10</version>
</dependency>
  • 配置消息转换器。

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

@Bean
public MessageConverter jsonMessageConverter(){return new Jackson2JsonMessageConverter();
}
http://www.lryc.cn/news/217768.html

相关文章:

  • 45基于matlab的ARIMA:AutoregressiveIntegratedMovingAverage model。
  • 2010年408计网
  • 初谈Linux-Linux环境搭建(阿里云免费服务器+xshell)
  • 如何利用AppScan扫描H5页面,进行安全测试?
  • Oracle数据库中的table@xyz是什么意思?
  • springboot常见网络相关错误及原因解析
  • 【C语言_线程pthread_互斥锁mutex_条件触发cond 之解析与示例 (开源)】.md updata:23/11/03
  • mongodb如何删除数据并释放空间
  • k8s之集群调度
  • 代码随想录算法训练营第四十二天丨 动态规划part05
  • [css] flex 子元素自动撑开父元素宽度
  • 全新干货!一招教你迅速提升流量主收入!包你轻松月入过万
  • 连接两个dataframe
  • 【入门Flink】- 05Flink运行时架构以及一些核心概念
  • 网络协议的基本概念
  • 广汽传祺E9上市,3DCAT实时云渲染助力线上3D高清看车体验
  • resource manager attributes structure(iofunc_attr_t) 扩展实例
  • 劳易测扫码条码分段读取实现方法
  • 【Linux】Nignx及负载均衡动静分离
  • AI:50-基于深度学习的柑橘类水果分类
  • mysql 中!= 到底走不走索引?
  • 4 sql语法基础
  • 网络工程师应知应会:基础知识(5)
  • Minio多节点多驱动分布式部署官网文档翻译
  • python连接clickhouse (CK)
  • 【C++】内联函数一看就懂?
  • 非洲“支付宝”PalmPay搭载OceanBase:成本降低80%
  • EASYX图片操作
  • 多测师肖sir_高级金牌讲师__adb命令
  • 块级作用域的理解