1. 什么是MQ
MQ
(Message Quene) : 即 消息队列
、 消息中间件
,通过典型的 生产者
和消费者
模型,生产者不断向消息队列中生产消息,消费者不断的从队列中获取消息。因为消息的生产和消费都是异步的,而且只关心消息的发送和接收,没有业务逻辑的侵入,轻松的实现系统间解耦。它通过利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。
2.RabbitMQ
官网下载地址
: https://www.rabbitmq.com/download.html
2.1 web管理界面介绍
-
connections:无论生产者还是消费者,都需要与RabbitMQ建立连接后才可以完成消息的生产和消费,在这里可以查看连接情况
-
channels:通道,建立连接后,会形成通道,消息的投递获取依赖通道。
-
Exchanges:交换机,用来实现消息的路由
-
Queues:队列,即消息队列,消息存放在队列中,等待消费,消费后被移除队列。
2.2 用户添加
上面的Tags选项,可以选择用户权限,权限选项如下:
-
超级管理员(administrator)
可登陆管理控制台,可查看所有的信息,并且可以对用户,策略(policy)进行操作。
-
监控者(monitoring)
可登陆管理控制台,同时可以查看rabbitmq节点的相关信息(进程数,内存使用情况,磁盘使用情况等)
-
策略制定者(policymaker)
可登陆管理控制台, 同时可以对policy进行管理。但无法查看节点的相关信息(上图红框标识的部分)。
-
普通管理者(management)
仅可登陆管理控制台,无法看到节点信息,也无法对策略进行管理。
-
其他
无法登陆管理控制台,通常就是普通的生产者和消费者。
2.3 创建虚拟主机
- 虚拟主机:为了让各个用户可以互不干扰的工作,RabbitMQ添加了虚拟主机(Virtual Hosts)的概念。其实就是一个独立的访问路径,不同用户使用不同路径,各自有自己的队列、交换机,互相不会影响。
2.4 用户与虚拟主机绑定
① 新建虚拟主机:
② 新建用户
③ 绑定虚拟主机
3.RabbitMQ的消息模型
3.1 AMQP协议模型
3.2 RabbitMQ支持的消息模型
3.2.1 引入依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.2</version>
</dependency>
3.2.2 “Hello World”模式
在上图的模型中,有以下概念:
- P:生产者,消息生产者
- C:消费者,消息消费者
- queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。
1)消息生产者代码
public class Provider
{
//生产消息
@Test
public void testSendMessage() throws IOException, TimeoutException
{
//创建连接mq的连接工厂对象
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置连接rabbitmq主机
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
//设置连接哪个虚拟主机
connectionFactory.setVirtualHost("lucky");
//设置访问虚拟主机的用户名和密码
connectionFactory.setUsername("luckyUser");
connectionFactory.setPassword("123");
//获取连接对象
Connection connection = connectionFactory.newConnection();
//获取连接中通道
Channel channel = connection.createChannel();
//通道绑定对应消息队列
//参数1:队列名称 如果队列中不存在会自动创建
//参数2:用来定义队列特性是否持久化 true持久化队列 false 不持久化 而非队列中消息
//参数3:exclusive 是否独占队列 true 独占队列
//参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除
//参数5: 附加参数
channel.queueDeclare("hello",true,false,false,null);
//发布消息
//参数1:交换机名称 参数2:队列名称 参数3:传递消息额外设置 MessageProperties.PERSISTENT_TEXT_PLAIN 消息也持久化 (需要保证生产者与消费者参数一致) 参数4:消息具体内容
channel.basicPublish("","hello", MessageProperties.PERSISTENT_TEXT_PLAIN,"hello rabbitmq".getBytes());
channel.close();
connection.close();
}
}
2)消息消费者代码
public class Customer
{
public static void main(String[] args) throws IOException, TimeoutException
{
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("lucky");
connectionFactory.setUsername("luckyUser");
connectionFactory.setPassword("123");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("hello",true,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("新消息"+new String(body));
}
});
//消费者一般不会关闭通道和连接,这时会一直监听
// channel.close();
// connection.close();
}
}
3)启动消费者和生产者,生产者收到消息
3.2.3 RabbitMQUtils
由上面代码可以看出,消息生产者和消费者的代码有大量重复的,所以我们可以对重复代码进行提取复用:
public class RabbitMQUtils
{
private static ConnectionFactory connectionFactory;
static {
connectionFactory = new ConnectionFactory();
//设置连接rabbitmq主机
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
//设置连接哪个虚拟主机
connectionFactory.setVirtualHost("lucky");
//设置访问虚拟主机的用户名和密码
connectionFactory.setUsername("luckyUser");
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 (IOException | TimeoutException e) {
e.printStackTrace();
}
}
}
3.2.4 “work quene”模式
Work queues
任务模型:当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work 模型:让多个消费者绑定到一个队列,共同消费队列中的消息。队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的。
在上图的模型中,有以下概念:
- P:生产者:任务的发布者
- C1:消费者-1:领取任务并完成任务;
- C2:消费者-2:领取任务并完成任务;
1)消息生产者代码
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 < 10; i++) {
channel.basicPublish("","work",null,("hello work queue "+i).getBytes());
}
RabbitMQUtils.closeConnectionAndChanel(channel,connection);
}
}
2)消息消费者代码
public class consumer1
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
final 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("消费者1"+new String(body));
}
});
}
}
public class consumer2
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare("work",true,false,false,null);
//参数2 true消息自动确认 消费者自动向rabbitmq确认消息消费
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将按顺序将每个消息发送给下一个使用者。平均而言,每个消费者都会收到相同数量的消息。
出现这种情况是因为我们在 channel.basicConsume(“work”,true,new DefaultConsumer(channel)中的第二个参数设置为true,表示消息会自动确认,即只要消费者拿到消息,就会告诉生产者消费成功,不管最后是否真正消费成功,生产者会将消息队列中的消息继续发给该消费者,这将可能导致消息丢失。在实际中,我们不希望这种情况发生,而且会根据各个消费者消费速度和能力,能者多劳,而不是平均分配。所以我们修改代码如下:
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);//手动确认消息
}
});
并人为将消费者1延迟一定时间,模拟消费能力差的情况,看是否还是平均分配:
channel.basicConsume("work",false,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException
{
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者1"+new String(body));
//手动确认 参数1:手动确认消息标识 参数2:false 每次确认一个
channel.basicAck(envelope.getDeliveryTag(),false);
}
});
由上图看出,消费者1因为消费速度慢导致获得了更少的消息。
3.2.5 “fanout”模式
在fanout模式下,消息发送流程如下:
- 可以有多个消费者
- 每个消费者都有自己的queue(队列)
- 每个队列都要绑定到Exchange(交换机)
- 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。
- 交换机把消息发送给绑定过的所有队列
- 队列的消费者都能拿到消息,实现一条消息被多个消费者消费。
1)消息生产者代码
public class Provider
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//将通道声明指定交换机 参数1:交换机名称 参数2:交换机类型 fanout广播类型
channel.exchangeDeclare("fanout_message","fanout");
//发送消息
channel.basicPublish("fanout_message","",null,"fanout type".getBytes());
RabbitMQUtils.closeConnectionAndChanel(channel,connection);
}
}
2)消息消费者代码(多个消费者代码相同)
public class customer
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//通道绑定交换机
channel.exchangeDeclare("fanout_message","fanout");
//l临时队列
String queue = channel.queueDeclare().getQueue();
//绑定交换机和队列
channel.queueBind(queue,"fanout_message","");
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(new String(body));
}
});
}
}
由上图看出,三个消费者均受到信息。
3.2.6 “Routing”模式
在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Routing。
在Routing模型下:
- 队列与交换机的绑定,不能是任意绑定了,而是要指定一个
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 的消息。
1)消息生产者代码
public class Provide
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//交换机名称, direct:路由模式
channel.exchangeDeclare("provide_direct","direct");
//发送消息
String key = "error";//error信息
channel.basicPublish("provide_direct",key,null,("这是direct模型基于route key"+key).getBytes());
RabbitMQUtils.closeConnectionAndChanel(channel,connection);
}
}
2)消费者1代码
public class customer
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//通道绑定交换机
channel.exchangeDeclare("provide_direct","direct");
//l临时队列
String queueName = channel.queueDeclare().getQueue();
//基于路由key绑定交换机和队列
channel.queueBind(queueName,"provide_direct","error");//接收error相关信息
channel.basicConsume(queueName,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException
{
System.out.println("error"+new String(body));
}
});
}
}
3)消费者2代码
public class customer2
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//通道绑定交换机
channel.exchangeDeclare("provide_direct","direct");
//l临时队列
String queueName = channel.queueDeclare().getQueue();
//基于路由key绑定交换机和队列 接收info、error和warning信息
channel.queueBind(queueName,"provide_direct","info");
channel.queueBind(queueName,"provide_direct","error");
channel.queueBind(queueName,"provide_direct","warning");
channel.basicConsume(queueName,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException
{
System.out.println("info+error+warning"+new String(body));
}
});
}
}
由上两张图可以看出,由于两个消费者均含有error的路由key,所以都收到了error相关消息,那我们试一下发info信息:
由上两张图看出,消费者2的路由key含有info,所以当生产者的路由key为info时,消费者2可以收到信息,而消费者1由于没有info的路由key,收不到信息。
3.2.7 “Topics”模式
Topic
类型的Exchange
与Routing
相比,都是可以根据RoutingKey
把消息路由到不同的队列。只不过Topic
类型Exchange
可以让队列在绑定Routing key
的时候使用通配符!这种模型Routingkey
一般都是由一个或多个单词组成,多个单词之间以”.”分割,例如: lucky.dog
.
- 统配符
* 匹配不多不少恰好1个词
# 匹配一个或多个词 - 如:
lucky.# 匹配lucky.dog.cat或者 lucky.dog等
lucky.* 只能匹配 audit.dog
1)消息生产者代码
public class Provide
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("topic_message","topic");
String routekey = "lucky.dog";
channel.basicPublish("topic_message",routekey,null,"topic动态路由模型".getBytes());
RabbitMQUtils.closeConnectionAndChanel(channel,connection);
}
}
2)消费者代码
public class customer1
{
public static void main(String[] args) throws IOException
{
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("topic_message","topic");
String queue = channel.queueDeclare().getQueue();
//*是一个单词 #是多个
channel.queueBind(queue,"topic_message","lucky.*");
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(new String(body));
}
});
}
}
4.SpringBoot中使用RabbitMQ
4.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
4.2 配置文件
spring:
application:
name: rabbitmq-springboot
rabbitmq:
host: 127.0.0.1
port: 5672
username: luckyUser
password: 123
virtual-host: lucky
4.3 “Hello World”模式
生产者:
@SpringBootTest(classes = DemoApplication.class)
@RunWith(SpringRunner.class)
public class TestRabbitMQ
{
//注入rabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
//hello world
@Test
public void testHello()
{
rabbitTemplate.convertAndSend("hello","hello world");
}
}
消费者:
@Component //默认是持久化 非独占 不自动删除的队列
@RabbitListener(queuesToDeclare = @Queue(value = "hello",durable = "true",autoDelete = "false"))//代表消费者 queuesToDeclare创建一个队列
public class HelloCustomer
{
@RabbitHandler
public void receive(String message)
{
System.out.println("message = "+message);
}
}
4.4 “work quene”模式
生产者:
//work
@Test
public void testWork()
{
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("work","work 模型");
}
}
消费者:
@Component
public class WorkCustomer
{
//放到方法上代表这个方法会处理接收到的消息,不需要handler
//一个消费者
@RabbitListener(queuesToDeclare = @Queue(value = "work"))
public void receive1(String message)
{
System.out.println(" work Message1"+message);
}
//放到方法上代表这个方法会处理接收到的消息,不需要handler
//一个消费者
@RabbitListener(queuesToDeclare = @Queue(value = "work"))
public void receive2(String message)
{
System.out.println(" work Message2"+message);
}
}
4.5 “fanout”模式
生产者:
//fanout广播
@Test
public void testFanout()
{
rabbitTemplate.convertAndSend("logs","","fanout模型");
}
消费者:
@Component
public class FanoutCustomer
{
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,//不指定名字则是临时队列
exchange = @Exchange(value = "logs",type = "fanout") //绑定的交换机
)
})
public void receive1(String message)
{
System.out.println("message1 fanout " + message);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,//不指定名字则是临时队列
exchange = @Exchange(value = "logs",type = "fanout") //绑定的交换机
)
})
public void receive2(String message)
{
System.out.println("message2 fanout " + message);
}
}
4.6 “Routing”模式
生产者:
//route 路由模式
@Test
public void testRoute()
{
rabbitTemplate.convertAndSend("directs","error","route模型");
}
消费者:
@Component
public class RouteCustomer
{
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,//临时队列
exchange = @Exchange(value = "directs",type = "direct"),
key = {"info","error","warn"}
)
})
public void receive1(String message)
{
System.out.println("message11" + message);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,//临时队列
exchange = @Exchange(value = "directs",type = "direct"),
key = {"error"}
)
})
public void receive2(String message)
{
System.out.println("message22" + message);
}
}
4.7 “Topics”模式
生产者:
//topic 动态路由模式(订阅模式)
@Test
public void testTopic()
{
rabbitTemplate.convertAndSend("topics","order","order路由消息");
}
消费者:
@Component
public class TopicCustomer
{
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(type = "topic",name = "topics"),
key = {"user.*"}
)
})
public void receive(String message)
{
System.out.println("message1"+message);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(type = "topic",name = "topics"),
key = {"order.#","produce.#","user.*"}
)
})
public void receive2(String message)
{
System.out.println("message2"+message);
}
}
5.RabbitMQ应用场景
- 异步处理:比如注册成功后的发送短信消息或者邮件的操作就可以通过MQ进行异步处理;
- 应用解耦:比如库存系统和订单系统之间就可以通过消息队列进行解耦;
- 流量削峰:秒杀场景中限制高峰流量以避免压垮系统。