赞
踩
MQ (MessageQueue),消息队列,字面来看就是存放消息的队列。也就是事件驱动架构中的Broker。
同步调用的优点:
调用的问题:
耦合度高:
每次加入新的需求,都要修改原来的代码
性能和吞吐能力下降:
调用者需要等待服务提供者响应,如果调用链过长则响应时间等于每次调用的时间之和。
有额外的资源消耗:
调用链中的每个服务在等待响应过程中,不能释放请求占用的资源,高并发场景下会极度浪费系统资源
有级联失败问题:
如果服务提供者出现问题,所有调用方都会跟着出问题,如同多米诺骨牌一样,迅速导致整个微服务群故障
异步通信的优点:
异步通信的缺点:
docker pull rabbitmq:3-management
执行下面的命令来运行MQ容器:
docker run \
-e RABBITMQ_DEFAULT_USER=itcast \
-e RABBITMQ_DEFAULT_PASS=123321 \
--name mq \
--hostname mq1 \
-p 15672:15672 \
-p 5672:5672 \
-d \
rabbitmq:3-management
RabbitMQ中的几个概念:
常见的消息模型:
发布订阅(Publish、Subscribe),又根据交换机类型不同分为三种:
基本消息队列的消息发送流程:
基本消息队列的消息接收流程:
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.TimeoutException; public class PublisherTest { @Test public void testSendMessage() throws IOException, TimeoutException { // 1.建立连接 ConnectionFactory factory = new ConnectionFactory(); // 1.1.设置连接参数,分别是:主机名、端口号、vhost、用户名、密码 factory.setHost("192.168.88.130"); factory.setPort(5672); factory.setVirtualHost("/"); factory.setUsername("itcast"); factory.setPassword("123321"); // 1.2.建立连接 Connection connection = factory.newConnection(); // 2.创建通道Channel Channel channel = connection.createChannel(); // 3.创建队列 String queueName = "simple.queue"; channel.queueDeclare(queueName, false, false, false, null); // 4.发送消息 String message = "hello, rabbitmq!"; channel.basicPublish("", queueName, null, message.getBytes()); System.out.println("发送消息成功:【" + message + "】"); // 5.关闭通道和连接 channel.close(); connection.close(); } }
package com.lhs; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class ConsumerTest { public static void main(String[] args) throws IOException, TimeoutException { // 1.建立连接 ConnectionFactory factory = new ConnectionFactory(); // 1.1.设置连接参数,分别是:主机名、端口号、vhost、用户名、密码 factory.setHost("192.168.88.130"); factory.setPort(5672); factory.setVirtualHost("/"); factory.setUsername("itcast"); factory.setPassword("123321"); // 1.2.建立连接 Connection connection = factory.newConnection(); // 2.创建通道Channel Channel channel = connection.createChannel(); // 3.创建队列 String queueName = "simple.queue"; channel.queueDeclare(queueName, false, false, false, null); // 4.订阅消息 channel.basicConsume(queueName, true, new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { // 5.处理消息 String message = new String(body); System.out.println("接收到消息:【" + message + "】"); } }); System.out.println("等待接收消息。。。。"); } }
SpringAMQP是基于RabbitMQ封装的一套模板,并且还利用SpringBoot对其实现了自动装配,使用起来非常方便。
SpringAMQP提供了三个功能:
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: 192.168.88.130 # 主机名
port: 5672 # 端口
virtual-host: / # 虚拟主机
username: itcast # 用户名
password: 123321 # 密码
@SpringBootTest
public class SpringamqpTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void test01(){
String queueName = "simple.queue";
String msg = "hello world123 !";
rabbitTemplate.convertAndSend(queueName, msg);
System.out.println("发送消息完成!");
}
}
package com.lhs.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 + "】");
}
}
Work queues,也被称为(Task queues),任务模型。简单来说就是让多个消费者绑定到一个队列,共同消费队列中的消息。
@Test
public void test02(){
String queueName = "simple.queue";
String msg = "hello world!";
for (int i = 1; i <= 50; i++) {
rabbitTemplate.convertAndSend(queueName, msg + i);
}
System.out.println("发送消息完成!");
}
@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);
}
两个消费者各处理25条:
spring:
rabbitmq:
listener:
simple:
prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
Work模型的使用:
可以看到,在订阅模型中,多了一个exchange角色,而且过程略有变化:
Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!
在广播模式下,消息发送流程是这样的:
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "lhs.queue"),
exchange = @Exchange(name = "myExchange",type = ExchangeTypes.FANOUT)
))
public void listenFanoutExchangeMessage1(String msg) throws InterruptedException {
System.out.println("消费者3........接收到消息:【" + msg + "】" + LocalTime.now());
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "lhs.queue"),
exchange = @Exchange(name = "myExchange",type = ExchangeTypes.FANOUT)
))
public void listenFanoutExchangeMessage2(String msg) throws InterruptedException {
System.out.println("消费者4........接收到消息:【" + msg + "】" + LocalTime.now());
}
@Test
public void test03(){
String exchange = "myExchange";
String msg = "你好";
rabbitTemplate.convertAndSend(exchange,"",msg);
}
在Direct模型下:
RoutingKey
(路由key)RoutingKey
。Routing Key
进行判断,只有队列的Routingkey
与消息的 Routing key
完全一致,才会接收到消息@RabbitListener(bindings = @QueueBinding( value = @Queue(name = "lhs1.queue1"), exchange = @Exchange(name = "myExchange1",type = ExchangeTypes.DIRECT), key = {"red","yellow"} )) public void listenDirectExchangeMessage3(String msg) throws InterruptedException { System.out.println("消费者5........接收到消息:【" + msg + "】" + LocalTime.now()); } @RabbitListener(bindings = @QueueBinding( value = @Queue(name = "lhs1.queue2"), exchange = @Exchange(name = "myExchange1",type = ExchangeTypes.DIRECT), key = {"red","blue"} )) public void listenDirectExchangeMessage4(String msg) throws InterruptedException { System.out.println("消费者6........接收到消息:【" + msg + "】" + LocalTime.now()); }
@Test
public void test04(){
String exchange = "myExchange1";
String msg = "你好";
String key = "blue";
rabbitTemplate.convertAndSend(exchange,key,msg);
}
Topic
类型的Exchange
与Direct
相比,都是可以根据RoutingKey
把消息路由到不同的队列。只不过Topic
类型Exchange
可以让队列在绑定Routing key
的时候使用通配符!
Routingkey
一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert
通配符规则:
#
:匹配一个或多个词
*
:匹配不多不少恰好1个词
@RabbitListener(bindings = @QueueBinding( value = @Queue(name = "lhs2.queue1"), exchange = @Exchange(name = "myExchange2",type = ExchangeTypes.TOPIC), key = "china.#" )) public void listenTopicExchangeMessage1(String msg) throws InterruptedException { System.out.println("消费者7........接收到消息:【" + msg + "】" + LocalTime.now()); } @RabbitListener(bindings = @QueueBinding( value = @Queue(name = "lhs2.queue2"), exchange = @Exchange(name = "myExchange2",type = ExchangeTypes.TOPIC), key = "#.news" )) public void listenTopicExchangeMessage2(String msg) throws InterruptedException { System.out.println("消费者8........接收到消息:【" + msg + "】" + LocalTime.now()); }
@Test
public void test05(){
String exchange = "myExchange2";
String msg = "你好Topic";
String key = "china.n";
rabbitTemplate.convertAndSend(exchange,key,msg);
}
Spring对消息对象的处理是由org.springframework.amqp.support.converter.MessageConverter来处理的。而默认实现是SimpleMessageConverter,基于JDK的ObjectOutputStream完成序列化。
众所周知,JDK序列化存在下列问题:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.10</version>
</dependency>
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。