rabbitMQ
1 RabbitMQ简介
MQ(Message Quene) : 翻译为 消息队列,通过典型的 生产者和消费者模型,生产者不断向消息队列中生产消息,消费者不断的从队列中获取消息。
因为消息的生产和消费都是异步的,而且只关心消息的发送和接收,没有业务逻辑的侵入,轻松的实现系统间解耦。
别名为 消息中间件 通过利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。
当今市面上有很多主流的消息中间件,如老牌的ActiveMQ
、RabbitMQ
,炙手可热的Kafka
,阿里巴巴自主开发RocketMQ
等。
不同MQ的特点
- ActiveMQ
ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。
它是一个完全支持JMS规范的的消息中间件。丰富的API,多种集群架构模式让ActiveMQ在业界成为老牌的消息中间件,在中小型企业颇受欢迎!
- Kafka
Kafka是LinkedIn开源的分布式发布-订阅消息系统,目前归属于Apache顶级项目。
Kafka主要特点是基于Pull的模式来处理消息消费,追求高吞吐量,一开始的目的就是用于日志收集和传输。
0.8版本开始支持复制,不支持事务,对消息的重复、丢失、错误没有严格要求, 适合产生大量数据的互联网服务的数据收集业务。
- RocketMQ
RocketMQ是阿里开源的消息中间件,它是纯Java开发,具有高吞吐量、高可用性、适合大规模分布式系统应用的特点。
RocketMQ思路起源于Kafka,但并不是Kafka的一个Copy,它对消息的可靠传输及事务性做了优化
目前在阿里集团被广泛应用于交易、充值、流计算、消息推送、日志流式处理、binglog分发等场景
- RabbitMQ
RabbitMQ是使用Erlang语言开发的开源消息队列系统,基于AMQP协议来实现。
AMQP的主要特征是面向消息、队列、路由(包括点对点和发布/订阅)、可靠性、安全。
AMQP协议更多用在企业系统内对数据一致性、稳定性和可靠性要求很高的场景,对性能和吞吐量的要求还在其次。
AMQP(advanced message queuing protocol)在2003年时被提出,最早用于解决金融领不同平台之间的消息传递交互问题。
顾名思义,AMQP是一种协议,更准确的说是一种binary wire-level protocol(链接协议)。
这是其和JMS的本质差别,AMQP不从API层进行限定,而是直接定义网络交换的数据格式。
RabbitMQ比Kafka可靠,Kafka更适合IO高吞吐的处理,一般应用在大数据日志处理或对实时性(少量延迟),可靠性(少量丢数据)要求稍低的场景使用,比如ELK日志收集。
2 RabbitMQ环境部署
准备工作
下载好两个rpm包 版本也是对应好的 rabbitmq的和erlang
将两个软件上传到Linux上
安装工作
rpm -ivh erlang-xxx.rpm
erlang需要依赖插件socat,所以需要安装socat,rpm -ivh socat-xxx.rpm
rpm -ivh rabbitmq-xxx.rpm
erl -v,可查看erlang版本号
配置RabbitMQ
配置rabbitmq.config: 在
/etc/rabbitmq/
下默认是没有此文件,因此需要复制一份模板进行修改,并修改名称为rabbitmq.config默认安装完成后配置文件模板在: /usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example目录中,需要将配置文件复制到/etc/rabbitmq/目录中。
复制配置文件:cp /usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example /etc/rabbitmq/rabbitmq.config
修改配置文件:vim /etc/rabbitmq/rabbitmq.config
注意去掉
%%
,以及最后的,
逗号启动rabbitmq中的插件管理:rabbitmq-plugins enable rabbitmq_management
RabbitMQ服务的常见命令:
1、开启:systemctl start rabbitmq-server
2、关闭:systemctl stop rabbitmq-server
3、重启:systemctl restart rabbitmq-server
4、查看服务状态:systemctl status rabbitmq-server
5、自启动:systemctl enable rabbitmq-server
6、关闭自启动:systemctl stop rabbitmq-server
RabbitMQWeb管理界面及授权操作
web管理默认的端口是15672
可以选择关闭防火墙服务或者是放行15672端口。
- 关闭防火墙
systemctl disable firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
systemctl stop firewalld
- 开放端口号
firewall-cmd --list-all -- 查看开放端口号
firewall-cmd --add-port=15672/tcp --permanent -- 设置开放端口号
firewall-cmd --reload -- 重启防火墙
- 访问web管理界面
- 默认登录管理
username: guest
password: guest
- rabbitMQ管理命令行
1.服务启动相关
systemctl start|restart|stop|status rabbitmq-server
2.管理命令行 用来在不使用web管理界面情况下命令操作RabbitMQ
rabbitmqctl help -- 可以查看更多命令
3.插件管理命令行
rabbitmq-plugins enable|list|disable
3 RabbitMQ的第一个程序
3.1 依赖导入
<!-- 引入rabbitmq的相关依赖-->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.2</version>
</dependency>
3.2 第一种模型(直连)
P:生产者,也就是要发送消息的程序
C:消费者,消息的接受者,会一直等待消息的到来
queue:消息队列,红色部分。类似于也给邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息
开发生产者
// 生产消息
@Test
public void testSendMessage() throws IOException, TimeoutException {
// 创建连接mq的连接工厂对象
ConnectionFactory connectionFactory = new ConnectionFactory();
// 设置连接rabbitmq的主机
connectionFactory.setHost("192.168.153.129");
// 设置端口号
connectionFactory.setPort(5672);
// 设置连接哪个虚拟主机
connectionFactory.setVirtualHost("/ems");
// 设置访问虚拟主机的用户名和密码
connectionFactory.setUsername("ems");
connectionFactory.setPassword("123");
// 获取连接对象
Connection connection = connectionFactory.newConnection();
// 获取连接中通道
Channel channel = connection.createChannel();
// 通道绑定对应的消息队列
/**
* 参数1:queue,队列名称,如果队列不存在自动创建
* 参数2:durable,用来定义队列特性是否要持久化 true 持久化队列,false 不持久化
* 参数3:exclusive,是否独占队列
* 参数4:autoDelete:是否在消费完成后自动删除队列
* 参数5:额外付加参数
**/
channel.queueDeclare("hello", false, false, false, null);
// 发布消息
// 参数1:交换机名称 参数2:队列名称 参数3:传递消息额外设置 参数4:消息的具体内容
channel.basicPublish("", "hello", null, "Hello RabbitMQ".getBytes());
// 资源关闭
channel.close();
connection.close();
}
开发消费者
// 消费消息,注意不能通过单元测试运行消费者
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.153.129");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/ems");
connectionFactory.setUsername("ems");
connectionFactory.setPassword("123");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("hello", false, false, false, null);
/**
* 参数1:消费哪个队列的消息 队列名称
* 参数2:开始消息的自动确认机制
* 参数3:消费时的回调接口
**/
channel.basicConsume("hello", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("this queue message: " + new String(body));
}
});
//消费者应该是处于一直消费的状态,因此建议不关闭
// channel.close();
// connection.close();
}
RabbitMQ连接工具类封装
public class RabbitMQUtils {
private static ConnectionFactory connectionFactory;
static {
// 重量级资源 类加载执行之前执行一次
connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.153.129");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/ems");
connectionFactory.setUsername("ems");
connectionFactory.setPassword("123");
}
// 定义提供连接对象的方法
public static Connection getConnection() {
try {
return connectionFactory.newConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return null;
}
// 关闭通道和关闭连接工具方法
public static void closeConnectionAndChanel(Channel channel, Connection connection) {
try {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.3 第二种模型(work queue)
Work queues,也被称为(Task queues),任务模型。当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。
长此以往消息就会堆积越来越多,无法及时处理。此时就可以使用work模型: 让多个消费者绑定到一个队列,共同消费队列中的消息。
队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的。
- P : 生产者: 任务的发布者
- C1∶消费者1: 领取任务并且完成任务,假设完成速度较慢
- C2∶消费者2︰领取任务并完成任务,假设完成速度快
开发生产者
public class Provider {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("work", true, false, false, null);
for (int i = 0; i < 22; i++) {
channel.basicPublish("", "work", null, (i + " hello work").getBytes());
}
RabbitMQUtils.closeConnectionAndChanel(channel, connection);
}
}
开发消费者1
public class Customer1 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("work", true, false, false, null);
channel.basicConsume("work", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
try {
Thread.sleep(4000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("消费者-1: " + new String(body));
}
});
}
}
开发消费者2
public class Customer2 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("work", true, false, false, null);
channel.basicConsume("work", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者-2: " + new String(body));
}
});
}
}
小总结:
默认情况下,RabbitMQ将按顺序将每个消息发送给下一个使用者。平均而言,每个消费者都会收到相同数量的消息。这种分发消息的方式称为循环。
但是当某个线程比较慢的时候,就会导致队列消息堆积,因此希望采用能者多劳的方式进行处理。
消息自动确认机制
Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code, once RabbitMQ delivers a message to the consumer it immediately marks it for deletion. In this case, if you kill a worker we will lose the message it was just processing. We’ll also lose all the messages that were dispatched to this particular worker but were not yet handled.
But we don’t want to lose any tasks. If a worker dies, we’d like the task to be delivered to another worker.
- 能者多劳的实现
// 一次只接受一条未确认的消息
channel.basicQos(1);
// 参数2:关闭自动确认消息
channel.basicConsume("hello",false,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1: "+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);//手动确认消息
}
});
设置通道一次只能消费一个消息 (谁比较慢给谁设置)
关闭消息的自动确认
开启手动确认消息
3.4 第三种模型(fanout)
fanout 扇出 也称为广播
在广播模式下,消息发送流程是这样的:
可以有多个消费者
每个消费者有自己的queue(队列)
每个队列都要绑定到Exchange(交换机)
生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。
交换机把消息发送给绑定过的所有队列
队列的消费者都能拿到消息。实现一条消息被多个消费者消费
开发生产者
public class Provider {
public static void main(String[] args) throws IOException {
// 获取连接对象
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机,参数1: 交换机名称 参数2:交换机类型 fanout 广播类型
channel.exchangeDeclare("logs", "fanout");
//发布消息
channel.basicPublish("logs", "", null, "fanout hello".getBytes());
// 释放资源
RabbitMQUtils.closeConnectionAndChanel(channel, connection);
}
}
开发消费者-1
public class Customer2 {
public static void main(String[] args) throws IOException {
// 获取连接
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
// 通道绑定交换机
channel.exchangeDeclare("logs", "fanout");
// 创建临时队列
String queue = channel.queueDeclare().getQueue();
// 将临时队列绑定exchange
channel.queueBind(queue, "logs", "");
// 处理消息
channel.basicConsume(queue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2: " + new String(body));
}
});
}
}
3.5 第四种模型(Routing)
Routing 之订阅模型-Direct(直连)
在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。
这时就要用到Direct类型的Exchange。
在Direct模型下:
队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)
消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey。Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行判断,只有队列的Routingkey与消息的 Routing key完全一致,才会接收到消息
P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。
X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列
C1:消费者,其所在队列指定了需要routing key 为 error 的消息
C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息
- 生产者
public class Provider {
public static void main(String[] args) throws IOException {
// 获取连接对象
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机,参数1: 交换机名称 参数2:交换机类型 direct 路由模式
channel.exchangeDeclare("logs_direct", "direct");
// 发送消息
String routingKey = "info";
channel.basicPublish("logs_direct", routingKey, null, ("这是direct模式:基于route key " + routingKey + "发送消息").getBytes());
// 关闭资源
RabbitMQUtils.closeConnectionAndChanel(channel, connection);
}
}
- 消费者1
public class Customer1 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare("logs_direct", "direct");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//绑定队列和交换机
channel.queueBind(queue, "logs_direct", "error");
//消费消息
channel.basicConsume(queue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1: " + new String(body));
}
});
}
}
- 消费者2
public class Customer2 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare("logs_direct", "direct");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//绑定队列和交换机
channel.queueBind(queue, "logs_direct", "error");
channel.queueBind(queue, "logs_direct", "info");
channel.queueBind(queue, "logs_direct", "warn");
//消费消息
channel.basicConsume(queue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1: " + new String(body));
}
});
}
}
Routing 之订阅模型-Topic
Topic类型的Exchange与Direct相比,都是可以根据RoutingKey把消息路由到不同的队列。
只不过Topic类型Exchange可以让队列在绑定Routing key的时候使用通配符!
这种模型Routingkey 一般都是由一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert
统配符
* (star) can substitute for exactly one word. 匹配不多不少恰好1个词
# (hash) can substitute for zero or more words. 匹配一个或多个词
如:
audit.# 匹配audit.irs.corporate或者 audit.irs 等
audit.* 只能匹配 audit.irs
- 生产者
public class Provider {
public static void main(String[] args) throws IOException {
// 获取连接对象
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机,参数1: 交换机名称 参数2:交换机类型 topic 动态路由模式
channel.exchangeDeclare("topics", "topic");
// 发送消息
String routingKey = "user.save.getUser";
channel.basicPublish("topics", routingKey, null, ("这是topic动态路由模式:基于route key " + routingKey + "发送消息").getBytes());
// 关闭资源
RabbitMQUtils.closeConnectionAndChanel(channel, connection);
}
}
- 消费者1(Routing Key中使用*通配符方式)
public class Customer1 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare("topics", "topic");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//绑定队列和交换机
channel.queueBind(queue, "topics", "user.*");
//消费消息
channel.basicConsume(queue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1: " + new String(body));
}
});
}
}
- 消费者2(Key中使用#通配符方式)
public class Customer2 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare("topics", "topic");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//绑定队列和交换机
channel.queueBind(queue, "topics", "user.#");
//消费消息
channel.basicConsume(queue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2: " + new String(body));
}
});
}
}
4 SpringBoot中使用RabbitMQ
4.1 搭建初始环境
RabbitTemplate用来简化操作 使用时可直接在项目中注入即可使用
5.1.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
5.1.2 配置配置文件
spring:
application:
name: springboot_rabbitmq
rabbitmq:
host: 192.168.152.30
port: 5672
username: ems
password: 123
virtual-host: /ems
4.2 第一种直连模型使用
生产者
@SpringBootTest(classes = RabbitmqSpringbootApplication.class)
public class TestRabbitMQ {
@Autowired
// 注入rabbitTemplate
private RabbitTemplate rabbitTemplate;
@Test
public void testHello() {
rabbitTemplate.convertAndSend("hello", "hello world");
}
}
消费者
@Component
@RabbitListener(queuesToDeclare = @Queue("hello"))
public class HelloRabbitMQ {
@RabbitHandler
public void receive(String message) {
System.out.println("message: " + message);
}
}
4.3 第二种work模式
生产者
@Test
public void testWork() {
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("work", i + "work send");
}
}
消费者
@Component
public class WorkCustomer {
// 消费者1
@RabbitListener(queuesToDeclare = @Queue("work"))
public void receive1(String message) {
System.out.println("message1: " + message);
}
// 消费者2
@RabbitListener(queuesToDeclare = @Queue("work"))
public void receive2(String message) {
System.out.println("message2: " + message);
}
}
4.4 第三种广播模式
生产者
// 广播模式
@Test
public void testFanout() {
rabbitTemplate.convertAndSend("logs", "", "FanOut的模式发送消息");
}
消费者
@Component
public class TestFanOut {
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,// 没名称代表临时队列
exchange = @Exchange(value = "logs", type = "fanout") // 绑定交换机
)
})
public void receive1(String message) {
System.out.println("消费者1: +" + message);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,// 没名称代表临时队列
exchange = @Exchange(value = "logs", type = "fanout") // 绑定交换机
)
})
public void receive2(String message) {
System.out.println("消费者2: +" + message);
}
}
4.5 第四种路由模式
生产者
// 路由模式
@Test
public void testRout() {
rabbitTemplate.convertAndSend("directs","info","发送info的路由信息");
}
消费者
@Component
public class TestRouteCustomer {
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,// 创建临时队列
exchange = @Exchange(value = "directs", type = "direct"),// 定义交换机名称类型
key = {"error", "info"}
)
})
public void receive1(String message) {
System.out.println("消费者1:" + message);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,// 创建临时队列
exchange = @Exchange(value = "directs", type = "direct"),// 定义交换机名称类型
key = {"error"}
)
})
public void receive2(String message) {
System.out.println("消费者2:" + message);
}
}
4.6 第五种动态路由模式
生产者
// 订阅模式
@Test
public void testTopic() {
rabbitTemplate.convertAndSend("topic", "xxx.user.save.getUser", "user.save 路由发送消息");
}
消费者
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(type = "topic", name = "topic"),
key = {"#.#"}
)
})
public void receive1(String message) {
System.out.println("消费者1:" + message);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(type = "topic", name = "topic"),
key = {"user.save", "user.*"}
)
})
public void receive2(String message) {
System.out.println("消费者2:" + message);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(type = "topic", name = "topic"),
key = {"*.user.#"}
)
})
public void receive3(String message) {
System.out.println("消费者3:" + message);
}
}
5 MQ的应用场景
5.1 异步处理
场景说明:用户注册后,需要发注册邮件和注册短信,传统的做法有两种 1.串行的方式 2.并行的方式
串行方式: 将注册信息写入数据库后,发送注册邮件,再发送注册短信,以上三个任务全部完成后才返回给客户端。
这有一个问题是,邮件,短信并不是必须的,它只是一个通知,而这种做法让客户端等待没有必要等待的东西.
并行方式: 将注册信息写入数据库后,发送邮件的同时,发送短信,以上三个任务完成后,返回给客户端,并行的方式能提高处理的时间。
消息队列: 假设三个业务节点分别使用50ms,串行方式使用时间150ms,并行使用时间100ms。
虽然并行已经提高的处理时间,但是,前面说过,邮件和短信对我正常的使用网站没有任何影响,客户端没有必要等着其发送完成才显示注册成功,
应该是写入数据库后就返回, 消息队列: 引入消息队列后,把发送邮件,短信不是必须的业务逻辑异步处理
**由此可以看出,引入消息队列后,用户的响应时间就等于写入数据库的时间+写入消息队列的时间(可以忽略不计),引入消息队列后处理后,响应时间是串行的3倍,是并行的2倍。 **
5.2 应用解耦
场景:双11是购物狂节,用户下单后,订单系统需要通知库存系统,传统的做法就是订单系统调用库存系统的接口。
这种做法有一个缺点: 当库存系统出现故障时,订单就会失败。 订单系统和库存系统高耦合. 引入消息队列
订单系统:用户下单后,订单系统完成持久化处理,将消息写入消息队列,返回用户订单下单成功。
库存系统:订阅下单的消息,获取下单消息,进行库操作。 就算库存系统出现故障,消息队列也能保证消息的可靠投递,不会导致消息丢失.
5.3 流量削峰
场景: 秒杀活动,一般会因为流量过大,导致应用挂掉,为了解决这个问题,一般在应用前端加入消息队列。
作用:
1.可以控制活动人数,超过此一定阀值的订单直接丢弃(我为什么秒杀一次都没有成功过呢)
2.可以缓解短时间的高流量压垮应用(应用程序按自己的最大处理能力获取订单)
1.用户的请求,服务器收到之后,首先写入消息队列,加入消息队列长度超过最大值,则直接抛弃用户请求或跳转到错误页面.
2.秒杀业务根据消息队列中的请求信息,再做后续处理。
6 RabbitMQ的集群
6.1 普通集群(副本集群)
默认情况下: RabbitMQ代理操作所需的所有数据/状态都将跨所有节点复制。
这方面的一个例外是消息队列,默认情况下,消息队列位于一个节点上,尽管它们可以从所有节点看到和访问
核心解决问题: 当集群中某一时刻master节点宕机,可以对Quene中信息,进行备份
集群搭建
- 集群规划
# 0.集群规划
node1: 10.15.0.3 mq1 master 主节点
node2: 10.15.0.4 mq2 repl1 副本节点
node3: 10.15.0.5 mq3 repl2 副本节点
# 1.克隆三台机器主机名和ip映射
vim /etc/hosts加入:
10.15.0.3 mq1
10.15.0.4 mq2
10.15.0.5 mq3
node1: vim /etc/hostname 加入: mq1
node2: vim /etc/hostname 加入: mq2
node3: vim /etc/hostname 加入: mq3
# 2.三个机器安装rabbitmq,并同步cookie文件,在node1上执行:
scp /var/lib/rabbitmq/.erlang.cookie root@mq2:/var/lib/rabbitmq/
scp /var/lib/rabbitmq/.erlang.cookie root@mq3:/var/lib/rabbitmq/
# 3.查看cookie是否一致:
node1: cat /var/lib/rabbitmq/.erlang.cookie
node2: cat /var/lib/rabbitmq/.erlang.cookie
node3: cat /var/lib/rabbitmq/.erlang.cookie
# 4.后台启动rabbitmq所有节点执行如下命令,启动成功访问管理界面:
rabbitmq-server -detached
# 5.在node2和node3执行加入集群命令:
1.关闭 rabbitmqctl stop_app
2.加入集群 rabbitmqctl join_cluster rabbit@mq1
3.启动服务 rabbitmqctl start_app
# 6.查看集群状态,任意节点执行:
rabbitmqctl cluster_status
# 7.如果出现如下显示,集群搭建成功:
Cluster status of node rabbit@mq3 ...
[{nodes,[{disc,[rabbit@mq1,rabbit@mq2,rabbit@mq3]}]},
{running_nodes,[rabbit@mq1,rabbit@mq2,rabbit@mq3]},
{cluster_name,<<"rabbit@mq1">>},
{partitions,[]},
{alarms,[{rabbit@mq1,[]},{rabbit@mq2,[]},{rabbit@mq3,[]}]}]
6.2 镜像集群
镜像队列机制就是将队列在三个节点之间设置主从关系,消息会在三个节点之间进行自动同步,且如果其中一个节点不可用,并不会导致消息丢失或服务不可用的情况,提升MQ集群的整体高可用性。
集群搭建
# 0.策略说明
rabbitmqctl set_policy [-p <vhost>] [--priority <priority>] [--apply-to <apply-to>] <name> <pattern> <definition>
-p Vhost: 可选参数,针对指定vhost下的queue进行设置
Name: policy的名称
Pattern: queue的匹配模式(正则表达式)
Definition:镜像定义,包括三个部分ha-mode, ha-params, ha-sync-mode
ha-mode:指明镜像队列的模式,有效值为 all/exactly/nodes
all:表示在集群中所有的节点上进行镜像
exactly:表示在指定个数的节点上进行镜像,节点的个数由ha-params指定
nodes:表示在指定的节点上进行镜像,节点名称通过ha-params指定
ha-params:ha-mode模式需要用到的参数
ha-sync-mode:进行队列中消息的同步方式,有效值为automatic和manual
priority:可选参数,policy的优先级
# 1.查看当前策略
rabbitmqctl list_policies
# 2.添加策略
rabbitmqctl set_policy ha-all '^hello' '{"ha-mode":"all","ha-sync-mode":"automatic"}'
说明:策略正则表达式为 “^” 表示所有匹配所有队列名称 ^hello:匹配hello开头队列
# 3.删除策略
rabbitmqctl clear_policy ha-all
# 4.测试集群