物流网站建设与管理规划书,小程序开发小程序制作,国外那些网站做展厅比较好,国内营销策划公司1. 简介#xff1a;
SpringAMQP是基于RabbitMQ封装的一套模板#xff0c;并且还利用SpringBoot对其实现了自动装配#xff0c;使用起来非常方便。
SpringAmqp的官方地址#xff1a;https://spring.io/projects/spring-amqp SpringAMQP提供了三个功能#xff1a;
自动声…1. 简介
SpringAMQP是基于RabbitMQ封装的一套模板并且还利用SpringBoot对其实现了自动装配使用起来非常方便。
SpringAmqp的官方地址https://spring.io/projects/spring-amqp SpringAMQP提供了三个功能
自动声明队列、交换机及其绑定关系基于注解的监听器模式异步接收消息封装了RabbitTemplate工具用于发送消息
2.初步配置
1.引入依赖
在父工程或需要使用的模块中引入依赖
!--AMQP依赖包含RabbitMQ--
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-amqp/artifactId
/dependency2. 配置文件
配置MQ地址在publisher服务的application.yml中添加配置
spring:rabbitmq:host: 192.168.2.67 # rabbitMQ的ip地址port: 5672 # 端口username: rootpassword: 123456virtual-host: /listener:simple:prefetch: 1 # 每次只能获取一条消息处理完成才能获取下一个消息解析prefetch能者多劳
在spring中有一个简单的配置可以解决这个问题。我们修改consumer服务的application.yml文件添加配置
spring:rabbitmq:listener:simple:prefetch: 1 # 每次只能获取一条消息处理完成才能获取下一个消息3. 配置消息转换器
配置JSON转换器
在publisher和consumer两个服务中都引入依赖
dependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactId
/dependency或
dependencygroupIdcom.fasterxml.jackson.dataformat/groupIdartifactIdjackson-dataformat-xml/artifactIdversion2.9.10/version
/dependency配置消息转换器。
在启动类或配置类中都添加一个Bean即可
Bean
public MessageConverter jsonMessageConverter(){return new Jackson2JsonMessageConverter();
}4. 配置消息发送和消费
详见后面的五种方式选择合适的进行配置即可。
3. 五种使用队列方式
1.Basic Queue 简单队列模型
a. 发送消息
然后在publisher服务中编写测试类SpringAmqpTest并利用RabbitTemplate实现消息发送
注入RabbitTemplate使用RabbitTemplate发送消息
package cn.itcast.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);}
}b. 消息接收
然后在consumer服务的cn.itcast.mq.listener包中新建一个类SpringRabbitListener监听队列代码如下
package cn.itcast.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 】);}
}2. WorkQueue
a.简介
Work queues也被称为Task queues任务模型。简单来说就是让多个消费者绑定到一个队列共同消费队列中的消息。
当消息处理比较耗时的时候可能生产消息的速度会远远大于消息的消费速度。长此以往消息就会堆积越来越多无法及时处理。
此时就可以使用work 模型多个消费者共同处理消息处理速度就能大大提高了。
b.消息发送
这次我们循环发送模拟大量消息堆积现象。
在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);}
}c. 消息接收
要模拟多个消费者绑定同一个队列我们在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秒模拟任务耗时。
d.总结
Work模型的使用
多个消费者绑定到一个队列同一条消息只会被一个消费者处理通过设置prefetch来控制消费者预取的消息数量
3. Fanout - 广播
a. 简介
Fanout英文翻译是扇出我觉得在MQ中叫广播更合适。
广播将消息交给所有绑定到交换机的队列
在广播模式下消息发送流程是这样的
1 可以有多个队列2 每个队列都要绑定到Exchange交换机3 生产者发送的消息只能发送到交换机交换机来决定要发给哪个队列生产者无法决定4 交换机把消息发送给绑定过的所有队列5 ** 订阅队列的消费者都能拿到消息
我们的计划是这样的
创建一个交换机 itcast.fanout类型是Fanout创建两个队列fanout.queue1和fanout.queue2绑定到交换机itcast.fanout
b.声明队列和交换机跳过
这里做的是简单介绍可以直接跳过这里不需要配置后面使用注解直接配置接口
Spring提供了一个接口Exchange来表示所有不同类型的交换机
在consumer中创建一个类声明队列和交换机也可以直接使用注解在Listener位置进行队列和交换机的声明
package cn.itcast.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(itcast.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);}
}c. 消息发送
在publisher服务的SpringAmqpTest类中添加测试方法
Test
public void testFanoutExchange() {// 队列名称String exchangeName itcast.fanout;// 消息String message hello, everyone!;rabbitTemplate.convertAndSend(exchangeName, , message);
}d. 消息接收
在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 】);
}第二种使用注解绑定交换机和队列
RabbitListener(bindings QueueBinding(value Queue(name fanout.queue1),exchange Exchange(name itcast.fanout, type ExchangeTypes.FANOUT)
))
public void listenFanoutQueue1(String msg) {System.out.println(111: 消费者接收到fanout.queue1的消息【 msg 】);
}RabbitListener(bindings QueueBinding(value Queue(name fanout.queue2),exchange Exchange(name itcast.fanout, type ExchangeTypes.FANOUT)
))
public void listenFanoutQueue2(String msg) {System.out.println(222: 消费者接收到fanout.queue2的消息【 msg 】);
}4.Direct - 定向
a.简介
在Fanout模式中一条消息会被所有订阅的队列都消费。但是在某些场景下我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。
在Direct模型下
队列与交换机的绑定不能是任意绑定了而是要指定一个RoutingKey路由key消息的发送方在 向 Exchange发送消息时也必须指定消息的 RoutingKey。Exchange不再把消息交给每一个绑定的队列而是根据消息的Routing Key进行判断只有队列的Routingkey与消息的 Routing key完全一致才会接收到消息
案例需求如下 利用RabbitListener声明Exchange、Queue、RoutingKey 在consumer服务中编写两个消费者方法分别监听direct.queue1和direct.queue2 在publisher中编写测试方法向itcast. direct发送消息
b.消息发送
在publisher服务的SpringAmqpTest类中添加测试方法
Test
public void testSendDirectExchange() {// 交换机名称String exchangeName itcast.direct;// 消息String message 红色警报日本乱排核废水导致海洋生物变异惊现哥斯拉;// 发送消息rabbitTemplate.convertAndSend(exchangeName, red, message);
}c.消息接收
基于注解声明队列和交换机
基于Bean的方式声明队列和交换机比较麻烦Spring还提供了基于注解方式来声明。
在consumer的SpringRabbitListener中添加两个消费者同时基于注解来声明队列和交换机
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 】);
}d. 总结
描述下Direct交换机与Fanout交换机的差异
Fanout交换机将消息路由给每一个与之绑定的队列Direct交换机根据RoutingKey判断路由给哪个队列如果多个队列具有相同的RoutingKey则与Fanout功能类似
基于RabbitListener注解声明队列和交换机有哪些常见注解
QueueExchange
5. Topic - 通配符
a. 简介说明
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中编写测试方法向itcast. topic发送消息
b.消息发送
在publisher服务的SpringAmqpTest类中添加测试方法
/*** topicExchange
*/
Test
public void testSendTopicExchange() {// 交换机名称String exchangeName itcast.topic;// 消息String message 喜报孙悟空大战哥斯拉胜!;// 发送消息rabbitTemplate.convertAndSend(exchangeName, china.news, message);
}c.消息接收
在consumer服务的SpringRabbitListener中添加方法
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 】);
}d.总结
描述下Direct交换机与Topic交换机的差异
Topic交换机接收的消息RoutingKey必须是多个单词以 **.** 分割Topic交换机与队列绑定时的bindingKey可以指定通配符#代表0个或多个词*代表1个词
4. 各种解析
1. 为什么要配置消息转换器
a. 说明
之前说过Spring会把你发送的消息序列化为字节发送给MQ接收消息的时候还会把字节反序列化为Java对象。
只不过默认情况下Spring采用的序列化方式是JDK序列化。众所周知JDK序列化存在下列问题
数据体积过大有安全漏洞可读性差
我们来测试一下。
b. 测试默认转换器
我们修改消息发送的代码发送一个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服务
发送消息后查看控制台
c. 配置消息转换器
配置JSON转换器
在publisher和consumer两个服务中都引入依赖
dependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactId
/dependency或
dependencygroupIdcom.fasterxml.jackson.dataformat/groupIdartifactIdjackson-dataformat-xml/artifactIdversion2.9.10/version
/dependency配置消息转换器。
在启动类或配置类中都添加一个Bean即可
Bean
public MessageConverter jsonMessageConverter(){return new Jackson2JsonMessageConverter();
}2. 发布/订阅解析
a. 简介
发布订阅的模型如图
Spring提供了一个接口Exchange来表示所有不同类型的交换机
可以看到在订阅模型中多了一个exchange角色而且过程略有变化
Publisher生产者也就是要发送消息的程序但是不再发送到队列中而是发给X交换机Exchange交换机图中的X。一方面接收生产者发送的消息。另一方面知道如何处理消息例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作取决于Exchange的类型。Exchange有以下3种类型 Fanout广播将消息交给所有绑定到交换机的队列Direct定向把消息交给符合指定routing key 的队列Topic通配符把消息交给符合routing pattern路由模式 的队列 Consumer消费者与以前一样订阅队列没有变化Queue消息队列也与以前一样接收消息、缓存消息。
Exchange交换机只负责转发消息不具备存储消息的能力因此如果没有任何队列与Exchange绑定或者没有符合路由规则的队列那么消息会丢失
b. 总结
交换机的作用是什么
接收publisher发送的消息将消息按照规则路由到与之绑定的队列不能缓存消息路由失败消息丢失FanoutExchange的会将消息路由到每个绑定的队列
声明队列、交换机、绑定关系的Bean是什么
QueueFanoutExchangeBinding
3.关于消息类型
rabbitMQ的消息默认支持Object类型Spring会把你发送的消息序列化为字节发送给MQ接收消息的时候还会把字节反序列化为Java对象。
配置Json消息转换器发送的消息会被解析为Json格式到队列接收到消息会被反解析为对应的java对象所以发送和消费接收的对象格式一定需要一致。