1.Docker安装RabbitMQ
docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:management
2.RabbitMQ管理界面
http://localhost:15672/ guest guest
3.RabbitMQ工作流程
1)生产者发送消息到rabbitMq服务端的交换机(Exchange)
2)交换机收到消息,根据路由key(ROUTINKEY),将消息转发给匹配的队列Queue
3)Queue收到消息,将消息发送给订阅者
4)订阅者收到消息,发送ACK给队列确认收到消息
5)Queue收到确认消息,删除队列缓存中的此条消息
4.交换机的四种类型
1)direct(默认):点对点的方式,交换机会将消息发送给完全匹配ROUTING_KEY的Queue
2)fanout:广播式的,不管消息的ROUTING_KEY是什么,交换机都会将消息发送给所有绑定的Queue
3)topic:主题交换器,Exchange会将消息转发和ROUTING_KEY匹配模式相同的所有队列(即模糊匹配的方式)
4)headers忽略
5.SpringBoot整合RabbitMQ
1.使用RabbitMQ
Pom.xml引入amqp;RabbitAutoConfiguration就会自动生效
给容器中自动配置了
RabbitTemplate、AmqpAdmin、CachingConnectionFactory、RabbitMessagingTemplate
@EnableRabbit
1)创建交换机
Exchange directExchange = new DirectExchange("hello-java-exchange",true,false);
amqpAdmin.declareExchange(directExchange);
2)创建队列
Queue queue = new Queue("hello-java-queue",true,false,false);
amqpAdmin.declareQueue(queue);
3)绑定交换机和队列
Binding binding = new Binding("hello-java-queue",
Binding.DestinationType.QUEUE,
"hello-java-exchange",
"hello.java",
null);
amqpAdmin.declareBinding(binding);
4)发送消息
OrderReturnReasonEntity reasonEntity = new OrderReturnReasonEntity();
reasonEntity.setId(1L);
reasonEntity.setCreateTime(new Date());
reasonEntity.setName("reason");
reasonEntity.setStatus(1);
reasonEntity.setSort(2);
String msg = "Hello World";
//1、发送消息,如果发送的消息是个对象,会使用序列化机制,将对象写出去,对象必须实现Serializable接口
//2、发送的对象类型的消息,可以是一个json
rabbitTemplate.convertAndSend("hello-java-exchange","hello2.java",
reasonEntity,new CorrelationData(UUID.randomUUID().toString()));
5)监听接收消息(@RabbitListener、@RabbitHandler)
/**
* queues:声明需要监听的队列
* channel:当前传输数据的通道
*/
@RabbitListener(queues = {"hello-java-queue"})
public void revieveMessage(Message message, OrderReturnReasonEntity content) {
//拿到主体内容
byte[] body = message.getBody();
//拿到的消息头属性信息
MessageProperties messageProperties = message.getMessageProperties();
}
@RabbitListener、@RabbitHandler区别:
@RabbitListener可以标注在类、方法上,且必须指定监听某个队列
@RabbitHandler只能标注在方法上,需配合@RabbitListener使用,可用于根据接收参数区分不同的接收方法。
2.保证可靠消息:消息确认机制
1)生产端:使用确认回调方法
1.开启RabbitMQ确认回调配置,confirm
模式
# 开启发送端消息抵达Queue确认
spring.rabbitmq.publisher-returns=true
# 只要消息抵达Queue,就会异步发送优先回调returnfirm
spring.rabbitmq.template.mandatory=true
2.生产者应用的回调方法就会被触发来处理确认消息
rabbitTemplate.setConfirmCallback((correlationData,ack,cause) -> {
...
});
2)消费端,ack确认机制
1.自动确认
消息不是很重要,一定要消费,消费端接收到消息就是立即自动发送确认。
2.手动确认
# 手动ack消息,不使用默认的消费端确认
spring.rabbitmq.listener.simple.acknowledge-mode=manual
保证消息可靠的消费,消费端接收到消息,处理完业务代码,自己手动调发送确认。
//拿到的消息头属性信息
MessageProperties messageProperties = message.getMessageProperties();
// 通道内自增
long deliveryTag = messageProperties.getDeliveryTag();
// 确认消费
channel.basicAck(deliveryTag, false);
// 确认未消费
channel.basicNack(deliveryTag, false);