Rabbit MQ
同步通信的优点:
时效性较强,可以立即得到结果
同步通信的缺点:
耦合度高
性能和吞吐能力下降
有额外的资源消耗
有级联失败问题
异步通信的优点:
吞吐量提升:无需等待订阅者处理完成,响应更快速
故障隔离:服务没有直接调用,不存在级联失败问题
调用间没有阻塞,不会造成无效的资源占用
耦合度极低,每个服务都可以灵活插拔,可替换
流量削峰:不管发布事件的流量波动多大,都由Broker接收,订阅者可以按照自己的速度去处理事件
异步通信的缺点:
架构复杂了,业务没有明显的流程线,不好管理
需要依赖于 Broker 的可靠、安全、性能(吞吐能力)
异步调用方案
异步调用常见实现就是事件驱动模式(Broker)
事件驱动优势
1、服务解耦
2、性能提升,吞吐量提高
3、服务没有强依赖,不担心级联失败问题
4、流量削峰
什么是MQ
MQ(MessageQueue),中文是消息队列,字面来看就是存放消息的队列。也就是事件驱动架构中的 Broker
消息模型
简单队列
Spring AMQP
什么是 AMQP
- 应用间消息通信的一种协议,与语言和平台无关。
什么是 Spring AMQP
是基于 AMQP 协议定义的一套 API 规范,提供了模板来发送和接收消息。包含两部分,其中 Spring-amqp是基础抽象,spring-rabbit 是底层的默认实现。
特征
- 侦听器容器,用于异步处理入站消息
- 用于发送和接收消息的 RabbitTemplate
- RabbitAdmin 用于自动声明队列,交换绑定
Spring AMQP 如何发送消息?
- 引入 amqp 的 starter 依赖
- 配置 RabbitMQ 地址
- 利用 RabbitTemplate 的 converAndSend 方法
Spring AMQP 如何接收消息?
- 引入 amqp 的 starter 依赖
- 配置 Rabbit MQ 地址
- 定义类,添加 @Component 注解
- 类中声明方法,添加 @Rabbit Listener 注解,方法参数就是消息
注意:消息一旦消费就会从队列删除,Rabbit MQ 没有消息回溯功能
Work Queue 工作队列
Work queue,工作队列,可以提高消息处理速度,避免队列消息堆积
模拟 WorkQueue,实现一个队列绑定多个消费者
基本思路:
- 在 publisher 服务中定义测试方法,每秒产生 50 条消息,发送到 simple.queue
- 在 consumer 服务中定义两个消息监听者,都监听 simple.queue 队列
- 消费者 1 每秒处理 50 条消息,消费者 2 每秒处理 10 条消息
消费预取限制
修改 application.yml 文件,设置 perFetch 这个值,可以控制预取消息的上限。
logging:
pattern:
dateformat: MM-dd HH:mm:ss:SSS
spring:
rabbitmq:
host: 192.168.182.128 # rabbitMQ的ip地址
port: 5672 # 端口
username: root
password: whz981113
virtual-host: /
# 消费预取限制
listener:
simple:
prefetch: 1
Work 模型的使用
- 多个消费者绑定到一个队列,同一条消费只会被一个消费者处理
- 通过设置 prefetch 来控制消费者预取的消息数量
发布(Publish)、订阅(Subscribe)
发布订阅模式与之前案例的区别就是允许将同一消息发送给多个消费者。实现方式是加入了 exchange(交换机)。
发布订阅 - Fanout Exchange
Fanout Exchange 会将接收到的消息路由到每一个跟其绑定的 queue
利用 Spring AMQP 演示 Fanout Exchange 的使用
实现思路:
- 在 consumer 服务中,利用代码声明队列、交换机,并将两者绑定
- 在 consumer 服务中,编写两个消费者方法,分别监听 fanout.queue1 和 fanout.queue2
- 在 publisher 中编写测试方法,向 itcast.fanout 发送消息
1、在 consumer 服务声明 Exchange、Queue、Binding
Spring AMQP 提供了声明交换机、队列、绑定关系的API
在 consumer 服务创建一个类,添加 @Configuration 注解,并声明 FanoutExchange、Queue 和绑定关系对象 Binding:
@Configuration
public class FanoutConfig {
// itcast.fanout
@Bean
public FanoutExchange fanoutExchange(){
return new FanoutExchange("itcast.fanout");
}
// fanout.queue1
@Bean
public Queue fanoutQueue1(){
return new Queue("fanout.queue1");
}
// 绑定队列1到交换机
@Bean
public Binding fanoutBinding1(Queue fanoutQueue1, FanoutExchange fanoutExchange){
return BindingBuilder
.bind(fanoutQueue1)
.to(fanoutExchange);
}
// fanout.queue2
@Bean
public Queue fanoutQueue2(){
return new Queue("fanout.queue2");
}
// 绑定队列2到交换机
@Bean
public Binding fanoutBinding2(Queue fanoutQueue2, FanoutExchange fanoutExchange){
return BindingBuilder
.bind(fanoutQueue2)
.to(fanoutExchange);
}
@Bean
public Queue objectQueue(){
return new Queue("object.queue");
}
}
在 consumer 服务的 Spring Rabbit Listener 类中,添加两个方法,分别监听 fanout.queue1 和 fanout.queue2
@RabbitListener(queues = "fanout.queue1")
public void listenFanoutQueue1(String msg) {
System.out.println("消费者接收到fanout.queue1的消息:【" + msg + "】");
}
@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String msg) {
System.out.println("消费者接收到fanout.queue2的消息:【" + msg + "】");
}
在 publisher 服务发送消息到 FanoutExchange
@Test
public void testSendFanoutExchange() {
// 交换机名称
String exchangeName = "itcast.fanout";
// 消息
String message = "hello, every one!";
// 发送消息
rabbitTemplate.convertAndSend(exchangeName, "", message);
}
交换机的作用
- 接收 publisher 发送的消息
- 将消息按照规则路由到与之绑定的队列
- 不能缓存消息,路由失败,消息丢失
- FanoutExchange 会将消息路由到每个绑定的队列
声明队列、交换机、绑定关系的 Bean 是什么?
- Queue
- FanoutExchange
- Binding
发布订阅 - DirectExchange
Direct Exchange 会将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes)
- 每一个 Queue 都与 Exchange 设置一个 BindingKey
- 发布者发送消息时,指定消息的 RoutingKey
- Exchange 将消息路由到 BingdingKey 与消息 RoutingKey 一致的队列
利用 Spring AMQP 演示 DirectExchange 的使用
1、利用 @RabbitListener 声明 Exchange(指定交换机名称、类型)、Queue(指定队列名称)、RoutingKey
编写两个消费者方法,分别监听 direct.queue1 和 direct.queue2
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "itcast.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 = "itcast.direct", type = ExchangeTypes.DIRECT),
key = {"red", "yellow"}
))
public void listenDirectQueue2(String msg){
System.out.println("消费者接收到direct.queue2的消息:【" + msg + "】");
}
利用 RoutingKey 指定消息发送到不同的用户
@Test
public void testSendDirectExchange() {
// 交换机名称
String exchangeName = "itcast.direct";
// 消息
String message = "hello, red!";
// 发送消息
rabbitTemplate.convertAndSend(exchangeName, "red", message);
}
描述 Direct 交换机与 Fanout 交换机的差异?
- Fanout 交换机将消息路由给每一个与之绑定的队列
- Direct 交换机根据 RoutingKey 判断路由给哪个队列
- 如果多个队列具有相同的 RoutingKey,则于 Fanout 功能类似
基于 @RabbitListener 注解声明队列和交换机有哪些常见注解?
- @Queue
- @Exchange
发布订阅 - TopicExchange
TopicExchange 与 DirectExchange 类似,区别在于 routingKey 必须是多个单词的列表,并且以 . 分割
#:代指 0 个或多个单词
*:代指一个单词
利用 Spring AMQP 演示 TopicExchange 的使用
实现思路:
1、利用 @RabbitListener 声明 Exchange、Queue、RoutingKey
2、在consumer 服务中,编写两个消费者方法,分别监听 topic.queue1 和 topic.queue2
@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 + "】");
}
3、在 publisher 中编写测试方法,向 itcast.topic 发送消息
@Test
public void testSendTopicExchange() {
// 交换机名称
String exchangeName = "itcast.topic";
// 消息
String message = "今天天气不错,我的心情好极了!";
// 发送消息
rabbitTemplate.convertAndSend(exchangeName, "china.weather", message);
}
Spring AMQP - 消息转换器
在 Spring AMQP 的发送方法中,接收消息的类型是 Object,也就是说我们可以发送任意对象类型的消息,Spring AMQP 会帮助我们序列化为字节后发送
Spirng 的消息对象的处理是由 org.springframework.amqp.support.converter.MessageConverter 来处理的。而默认实现是 SimpleMessageConverter,基于 JDK 的 ObjectOutputStream 完成序列化。
如果要修改只需要定义一个 MessageConverter 类型的 Bean 即可。推荐使用 JSON 方式序列化
发送
- 在 publisher 服务引入依赖(因为 consumer 也要用,直接引入父工程)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
- 在 publisher 服务声明 MessageConverter
@SpringBootApplication
public class PublisherApplication {
public static void main(String[] args) {
SpringApplication.run(PublisherApplication.class);
}
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
接收
- 导入依赖
- 在 consumer 服务定义 MessageConverter
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
- 定义消费者,监听 object.queue 队列并消费消息
@RabbitListener(queues = "object.queue")
public void listenObjectQueue(Map<String,Object> msg){
System.out.println("接收到object.queue的消息:" + msg);
}
Spring AMQP 中消息的序列化和反序列化是怎么实现的?
- 利用 MessageConverter 实现的,默认是 JDK 的序列化
- 注意发送方和接收方必须使用相同的 MessageConverter