RabbitMQ学习笔记
一 简介
1.1 引言
- 传统单体应用模块之间的耦合度过高,导致一个模块宕机后,全部功能都不能用了。
- 同步通讯的成本过高。
1.2 RabbitMQ的介绍
市场上比较常用的几个MQ:
ActiveMQ、RocketMQ、Kafka、RabbitMQ
- 语言支持:ActiveMQ,RocketMQ只支持Java语言,Kafka和RabbitMQ可以支持多种语言。
- 效率方面:ActiveMQ、RocketMQ、Kafka效率都是毫秒级别,RabbitMQ是微秒级别。
- 消息丢失,消息重复问题:RabbitMQ对消息的持久化,和重复问题都有比较成熟的方案。
- 学习成本:RabbitMQ非常简单。
RabbitMQ是有Rabbit公司研发和维护的,最终是在Pivotal
RabbitMQ严格遵守AMQP协议,高级消息队列协议,帮助我们在进程之间传递异步消息。
二 RabbitMQ安装
version: "3.1"
services:
rabbitmq:
image: daocloud.io/library/rabbitmq:3.8.4-management
restart: always
container_name: rabbitmq
ports:
- 5672:5672
- 15672:15672
volumes:
- ./data:/var/lib/rabbitmq
运行命令:docker-compose up -d
三 RabbitMQ架构
3.1 官方简单架构图
Publisher-生产者:发布消息到RabbitMQ的Exchange中
Consumer-消费者:监听RabbitMQ中的Queue中的消息
Exchange-交换机:和生产者建立连接并接收生产者的消息
Queue-队列:Exchange将消息分发给Queue,Queue和消费者进行交互
Routes-路由:交换机以什么策略将消息发布到Queue
3.2 完整架构图
3.3 查看图形化界面并创建一个Virtual Host
创建一个全新的用户(test)和全新的Virtual Host,并且将test用户设置可以操作/test的权限
四 RabbitMQ的使用
4.1 RabbitMQ的通讯方式
4.2 Java连接RabbitMQ
1.创建Maven项目
2.导入依赖
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3.创建工具类连接RabbitMQ
public static Connection getConnection() {
// 创建Connection工厂
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.75.139");
connectionFactory.setPort(5672);
connectionFactory.setUsername("test");
connectionFactory.setPassword("test");
connectionFactory.setVirtualHost("/test");
Connection connection = null;
try {
connection = connectionFactory.newConnection();
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
4.3 Hello-World
一个生产者,一个默认的交换机,一个队列,一个消费者
1.创建生产者,创建一个channel,发布消息到exchange中,指定路由规则。
@Test
public void publish() throws Exception {
// 1.创建Connection 快捷键:Ctrl+Alt+V 可以引入变量
Connection connection = RabbitMQClient.getConnection();
// 2.创建Channel
Channel channel = connection.createChannel();
// 3.发布消息到exchange,同时指定路由的规则
String msg = "Hello World!!!";
/**
* 参数:
* 1.指定exchange,使用""
* 2.指定路由的规则,使用具体的队列名称
* 3.指定传递的消息所携带的properties,使用null
* 4.指定发布具体的消息,byte[]类型
*/
channel.basicPublish("", "HelloWorld", null, msg.getBytes());
//PS:exchange不会帮你将消息持久化到本地的,Queue才会帮你持久化消息
System.out.println("生产者发布消息成功!");
// 4.释放资源
channel.close();
connection.close();
}
2.创建消费者,创建一个channel,创建一个队列,并且去消费当前队列。
@Test
public void consume() throws Exception {
// 1.创建连接
Connection connection = RabbitMQClient.getConnection();
// 2.创建一个channel
Channel channel = connection.createChannel();
// 3.声明队列-HelloWorld
/**
* 参数:
* 1.queue - 指定队列名称
* 2.durable - 当前队列是否持久化(true)
* 3.exclusive - 是否排外(connection.close() - 当前队列会被自动删除,当前队列只能被一个消费者消费)
* 4.autoDelete - 如果这个队列没有消费者消费,队列自动删除
* 5.arguments - 指定队列当前的其他信息
*/
channel.queueDeclare("HelloWorld", true, false, false, null);
// 4.开启监听队列
/**
* 参数
* 1.queue - 指定消费哪个队列
* 2.autoAck - 指定是否ACK(true,接收消息后,会立即告诉RabbitMQ)
* 3.consumer - 指定消费回调
*/
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接收到消息:" + new String(body, "UTF-8"));
}
};
channel.basicConsume("HelloWorld", true, consumer);
System.out.println("消费者开始监听队列!!!");
// System.in.read()
System.in.read();
// 5.释放资源
channel.close();
connection.close();
}
4.4 Work
一个生产者,一个默认的交换机,一个队列,两个消费者
只要在消费者端,添加Qos能力以及更改为手动ack即可让消费者,根据自己的能力去消费指定的消息,而不是默认情况下由RabbitMQ平均分配了
// 1.指定消费者,一次消费多少消息
channel.basicQos(1);
// 监听Queue
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("consumer1接收到消息:" + new String(body, "UTF-8"));
// 2.手动ACK
channel.basicAck(envelope.getDeliveryTag(), false);
}
};
// 3.指定手动ack
channel.basicConsume("Work", false, consumer);
4.5 Publish/Subscribe
一个生产者,一个交换机,两个队列,两个消费者
声明一个Fanout类型的exchange,并且将exchange和queue绑定一起,绑定的方式就是直接绑定。
1.让生产者创建一个exchange并且指定类型,和一个或多个队列绑定一起
// 3.创建exchange - 绑定某个队列
// 参数1:exchange名称
// 参数2:指定exchange的类型 FANOUT-pubsub,DIRECT-Routing,TOPIC-Topics
channel.exchangeDeclare("pubsub-exchange", BuiltinExchangeType.FANOUT);
channel.queueBind("pubsub-queue1", "pubsub-exchange", "");
channel.queueBind("pubsub-queue2", "pubsub-exchange", "");
2.消费者还是正常监听某个队列即可
4.6 Routing
一个生产者,一个交换机,两个队列,两个消费者
创建一个DIRECT类型的exchange,并且去根据RoutingKey绑定指定队列。
1.生产者创建DIRECT类型的exchange后,去绑定相应队列,并且在发消息时,指定消息的具体RoutingKey即可。
// 3.创建exchange - 绑定某个队列
// 参数1:exchange名称
// 参数2:指定exchange的类型 FANOUT-pubsub,DIRECT-Routing,TOPIC-Topics
channel.exchangeDeclare("routing-exchange", BuiltinExchangeType.DIRECT);
// 绑定routing-queue-error,routing-queue-info
channel.queueBind("routing-queue-error", "routing-exchange", "ERROR");
channel.queueBind("routing-queue-info", "routing-exchange", "INFO");
// 4.发布消息到exchange,同时指定路由的规则
channel.basicPublish("routing-exchange", "ERROR", null, "ERROE".getBytes());
channel.basicPublish("routing-exchange", "INFO", null, "INFO1".getBytes());
channel.basicPublish("routing-exchange", "INFO", null, "INFO2".getBytes());
channel.basicPublish("routing-exchange", "INFO", null, "INFO3".getBytes());
channel.basicPublish("routing-exchange", "INFO", null, "INFO4".getBytes());
2.消费者基本没变
4.7 Topic
一个生产者,一个交换机,两个队列,两个消费者
1.生产者创建Topic类型的exchange并且绑定到队列中,这次绑定可以通过*和#关键字,对指定RoutingKey内容,编写时注意格式xxx.xxx.xxx去编写,
*->一个xxx,而#->代表多个xxx.xxx,在发送消息时,指定具体的RoutingKey到底是什么。
// 3.创建exchange - 绑定某个队列
// 参数1:exchange名称
// 参数2:指定exchange的类型 FANOUT-pubsub,DIRECT-Routing,TOPIC-Topics
channel.exchangeDeclare("topic-exchange", BuiltinExchangeType.TOPIC);
/**
* 动物信息:<speed><color><what>
* *.red.* -> *占位符
* fast.# -> #通配符
* *.*.rabbit -> rabbit 兔子
*/
channel.queueBind("topic-queue-1", "topic-exchange", "*.red.*");
channel.queueBind("topic-queue-2", "topic-exchange", "fast.#");
channel.queueBind("topic-queue-2", "topic-exchange", "*.*.rabbit");
// 4.发布消息到exchange,同时指定路由的规则
channel.basicPublish("topic-exchange", "fast.red.monkey", null, "红快猴子".getBytes());
channel.basicPublish("topic-exchange", "slow.black.dog", null, "黑慢狗".getBytes());
channel.basicPublish("topic-exchange", "fast.white.cat", null, "快白猫".getBytes());
2.消费者基本没变,只是监听队列
五 RabbitMQ整合SpringBoot
5.1 SpringBoot整合RabbitMQ
1.创建SpringBoot工程
2.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3.编写配置文件
spring:
rabbitmq:
host: 192.168.75.139
port: 5672
username: test
password: test
virtual-host: /test
4.编写配置类,声明exchange和queue,并且绑定在一起
@Configuration
public class RabbitMQConfig {
// 1.创建exchange - topic
@Bean
public TopicExchange getTopicExchange() {
return new TopicExchange("springboot-topic-exchange", true, false);
}
// 2.创建队列
@Bean
public Queue getQueue() {
return new Queue("springboot-queue", true, false, false, null);
}
// 3.绑定在一起
@Bean
public Binding getBinding(TopicExchange topicExchange, Queue queue) {
return BindingBuilder.bind(queue).to(topicExchange).with("*.red.*");
}
}
- 发布消息到RabbitMQ
@SpringBootTest
class SpringbootRabbitmqApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
rabbitTemplate.convertAndSend("springboot-topic-exchange","slow.red.dog","红色大狼狗");
}
}
- 创建消费者监听消息
@Component
public class Consumer {
@RabbitListener(queues = "springboot-queue")
public void getMessage(Object msg) {
System.out.println("接收消息:" + msg);
}
}
5.2 手动Ack
- 添加配置文件
spring:
rabbitmq:
listener:
simple:
acknowledge-mode: manual
- 在消费者的位置,修改方法,再手动Ack
@RabbitListener(queues = "springboot-queue")
public void getMessage(String msg, Channel channel, Message message) throws IOException {
System.out.println("接收消息:" + msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
}
六 RabbitMQ的其他操作
6.1 消息可靠性
RabbitMQ的事务:事务可以确保消息100%传递,可以通过事务回滚去记录日志,后面定时再次发送当前消息。事务的操作,效率太低,添加事务后,比平时操作效率最少慢100倍。
6.1.1 Confirm机制
RabbitMQ除了事务,还提供了confirm的确认机制,这个效率比事务高很多。
1.普通Confirm方式
// 开启事务
channel.confirmSelect();
// 发送消息
String msg = "Hello World!!!";
channel.basicPublish("", "HelloWorld", null, msg.getBytes());
//判断消息是否发送成功
if(channel.waitForConfirms()){
System.out.println("消息发送成功");
}else{
System.out.println("消息发送失败");
}
2.批量Confirm方式
Channel channel = connection.createChannel();
// 开启事务
channel.confirmSelect();
String msg = "Hello World!!!";
//批量发送消息
for (int i = 0; i < 1000; i++) {
channel.basicPublish("", "HelloWorld", null, (msg + i).getBytes());
}
//确定批量操作是否成功
channel.waitForConfirmsOrDie();//当发送的消息,有一条失败的时候,就直接全部失败 抛出异常
3.异步Confirm方式
//开启事务
channel.confirmSelect();
String msg = "Hello World!!!";
for (int i = 0; i < 1000; i++) {
channel.basicPublish("", "HelloWorld", null, (msg + i).getBytes());
}
//开启异步回调
channel.addConfirmListener(new ConfirmListener() {
public void handleAck(long l, boolean b) throws IOException {
System.out.println("消息发送成功,标识" + l + ",是否是批量操作" + b);
}
public void handleNack(long l, boolean b) throws IOException {
System.out.println("消息发送失败,标识" + l + ",是否是批量操作" + b);
}
});
6.1.2 Return机制
Confire机制只能保证消息发送到exchange,不能保证消息可以被exchange分发到指定的queue中,exchange不能持久化消息,queue是可以持久化消息。
采用return机制,监听消息是否从exchange分发到queue中
1.开启Return机制
//开启return机制
channel.addReturnListener(new ReturnListener() {
@Override
public void handleReturn(int i, String s, String s1, String s2, AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
// 当消息没有
System.out.println(new String(bytes, "UTF-8") + "没有送达到Queue中!!!");
}
});
// 发送时指定mandatory参数true
channel.basicPublish("", "HelloWorld",true, null, (msg + i).getBytes());
6.1.3 SpringBoot实现Confirm以及Return
1.编写配置文件,开启Confirm和Return机制
spring:
rabbitmq:
publisher-confirm-type: simple
publisher-returns: true
2.指定RabbitTemplate对象,开启Confirm和Return,并且编写了回调方法
@Component
public class RabbitMQConfirmAndReturnConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
@Autowired
private RabbitTemplate rabbitTemplate;
@PostConstruct
public void initMethod() {
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnCallback(this);
}
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
if (ack) {
System.out.println("消息已经送达到Exchange");
} else {
System.out.println("消息没有送达到Exchange");
}
}
@Override
public void returnedMessage(Message message, int i, String s, String s1, String s2) {
System.out.println("消息没有送达到Queue");
}
}
6.2 避免消息重复消费
6.2.1 避免消息重复消费实现
为解决消息重复消费的问题,可以采用Redis,在消费者消费消息之前,先将消息的id放到Redis中,
id-0 (正在执行业务)
id-1 (执行业务成功)
如果ack失败,在RabbitMQ将消息交给其他消费者时,先执行setnx,如果key已经存在,获取他的值,如果是0,当前消费者什么都不做,如果是1,直接ack。
极端情况:第一个消费者消费的时候出现死锁,在setnx的基础上,在给key设置一个生存时间。
1.生产者,发送消息时,指定messageId
AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
.deliveryMode(1) //消息是否持久化 1 - 需要持久化 2- 不需要持久化
.messageId(UUID.randomUUID().toString())
.build();
String msg = "Hello World!!!";
// 指定properties
channel.basicPublish("", "HelloWorld", true, properties, (msg).getBytes());
2.消费者,在消费消息时,根据业务逻辑去操作redis
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
Jedis jedis = new Jedis("192.168.75.139", 6379);
String messageId = properties.getMessageId();
// 1.setnx到Redis中,默认指定value-0
String result = jedis.set(messageId, "0", "NX", "EX", 10);
if (result != null && result.equalsIgnoreCase("OK")) {
System.out.println("接收到消息:" + new String(body, "UTF-8"));
// 2.消费成功,set messageId 1
jedis.set(messageId, "1");
channel.basicAck(envelope.getDeliveryTag(), false);
} else {
// 3.如果1中的消费失败,获取对应的value,如果是0,return,如果是1,手动ack
String s = jedis.get(messageId);
if ("1".equalsIgnoreCase(s)) {
channel.basicAck(envelope.getDeliveryTag(), false);
}
}
}
};
6.2.2 SpringBoot如何实现
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.编写配置文件
spring:
redis:
host: 192.168.75.139
port: 6379
3.修改生产者
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
CorrelationData messageId = new CorrelationData(UUID.randomUUID().toString());
rabbitTemplate.convertAndSend("springboot-topic-exchange", "slow.red.dog", "红色大狼狗", messageId);
}
4.修改消费者
@RabbitListener(queues = "springboot-queue")
public void getMessage(String msg, Channel channel, Message message) throws IOException {
String messageId = message.getMessageProperties().getHeader("spring_returned_message_correlation");
// 1.设置key到Redis
if (redisTemplate.opsForValue().setIfAbsent(messageId, "0", 10, TimeUnit.SECONDS)) {
// 2.消费消息
System.out.println("接收消息:" + msg);
// 3.设置key的value值为1
redisTemplate.opsForValue().set(messageId, "1", 10, TimeUnit.SECONDS);
// 4.手动ack
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} else {
// 5.获取Redis中的value即可 如果是1,手动ack
if ("1".equalsIgnoreCase(redisTemplate.opsForValue().get(messageId))) {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
}
}
}