沧州网站建设icp备,做企业网站好的,伪春菜wordpress,app优化网站开发第十章 RabbitMQ
三、SpringAMQP SpringAMQP 是基于 RabbitMQ 封装的一套模板#xff0c;并且还利用 SpringBoot 对其实现了自动装配#xff0c;使用起来非常方便。 SpringAmqp 的官方地址#xff1a;https://spring.io/projects/spring-amqp SpringAMQP 提供了三个功能并且还利用 SpringBoot 对其实现了自动装配使用起来非常方便。 SpringAmqp 的官方地址https://spring.io/projects/spring-amqp SpringAMQP 提供了三个功能 自动声明队列、交换机及其绑定关系基于注解的监听器模式异步接收消息封装了 RabbitTemplate 工具用于发送消息
1. Basic Queue 简单队列模型
在父工程 mq-demo 中引入依赖
!--AMQP依赖包含RabbitMQ--
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-amqp/artifactId
/dependency1.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 是什么 QueueFanoutExchangeBinding
5. Direct
在 Fanout 模式中一条消息会被所有订阅的队列都消费。但是在某些场景下我们希望不同的消息被不同的队列消费。这时就要用到 Direct 类型的 Exchange。 在 Direct 模型下 队列与交换机的绑定不能是任意绑定了而是要指定一个RoutingKey路由 key消息的发送方在 向 Exchange 发送消息时也必须指定消息的 RoutingKeyExchange 不再把消息交给每一个绑定的队列而是根据消息的Routing Key进行判断只有队列的 Routingkey 与消息的 Routing key 完全一致才会接收到消息 案例需求如下 利用RabbitListener 声明 Exchange、Queue、RoutingKey 在 consumer 服务中编写两个消费者方法分别监听 direct.queue1 和 direct.queue2 在 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 注解声明队列和交换机有哪些常见注解 QueueExchange
6. Topic
6.1 说明 Topic类型的Exchange与Direct相比都是可以根据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.weatherQueue2绑定的是#.news 因此凡是以 .news结尾的 routing key 都会被匹配。包括 china.news 和 japan.news 案例需求(实现思路如下) 利用RabbitListener 声明 Exchange、Queue、RoutingKey 在 consumer 服务中编写两个消费者方法分别监听 topic.queue1 和 topic.queue2 在 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 {// 准备消息MapString,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 两个服务中都引入依赖
dependencygroupIdcom.fasterxml.jackson.dataformat/groupIdartifactIdjackson-dataformat-xml/artifactIdversion2.9.10/version
/dependency配置消息转换器。 在启动类中添加一个 Bean 即可
Bean
public MessageConverter jsonMessageConverter(){return new Jackson2JsonMessageConverter();
}