Spring Boot整合RabbitMQ实战
本篇文章将带你了解Rabbitmq,work模型,发布订阅模型,topic模型,生产者confirm消息确认机制,消费者确认机制,return消息机制,TTL队列,死信队列等相关操作
在springboot 中引入Rabbitmq
只需要在 pom.xml 中引入,版本跟随spingboot版本
pom.xml
org.springframework.boot
spring-boot-starter-amqp
${spring-boot.version}
application.properties
# rabbitmq
# 配置虚拟机
spring.rabbitmq.virtual-host=/
# 开启消息确认机制 confirm 异步
spring.rabbitmq.publisher-confirm-type=correlated
# 之前的旧版本 开启消息确认机制的方式
# spring.rabbitmq.publisher-confirms=true
# 开启return机制
spring.rabbitmq.publisher-returns=true
# 消息开启手动确认
spring.rabbitmq.listener.direct.acknowledge-mode=manual
spring.rabbitmq.listener.simple.acknowledge-mode=manual
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456
work模型
RabbitmqConfig.java
@SpringBootConfiguration
public class RabbitmqConfig {
// 配置一个工作模型队列
@Bean
public Queue queueWork1() {
return new Queue("queue_work");
}
}
不指定交换器和路由的话,会使用默认的交换器和路由
RabbitmqController.java
@RestController
public class RabbitmqController {
@Resource
private IRabbitmqService rabbitmqService;
/**
* 生产消费模式
*
* @return success
*/
@GetMapping("/sendWork")
public Object sendWork() {
rabbitmqService.sendWork();
return "发送成功...";
}
}
IRabbitmqService.java
public interface IRabbitmqService {
void sendWork();
}
RabbitmqService.java
@Service
public class RabbitmqService implements IRabbitmqService {
@Resource
private RabbitTemplate rabbitTemplate;
@Override
public void sendWork() {
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("queue_work", "测试work模型: " + i);
}
}
}
WorkReceiveListener.java
@Component
@Slf4j
public class WorkReceiveListener {
@RabbitListener(queues = "queue_work")
public void receiveMessage(String msg, Channel channel, Message message) {
// 只包含发送的消息
log.info("1接收到消息:" + msg);
// channel 通道信息
// message 附加的参数信息
}
@RabbitListener(queues = "queue_work")
public void receiveMessage2(Object obj, Channel channel, Message message) {
// 包含所有的信息
log.info("2接收到消息:{}", obj);
}
}
测试工作模型
http://127.0.0.1:8080/sendWork
控制台打印
发布订阅模型
RabbitmqConfig.java
// 发布订阅模式
// 声明两个队列
@Bean
public Queue queueFanout1() {
return new Queue("queue_fanout1");
}
@Bean
public Queue queueFanout2() {
return new Queue("queue_fanout2");
}
// 准备一个交换机
@Bean
public FanoutExchange exchangeFanout() {
return new FanoutExchange("exchange_fanout");
}
// 将交换机和队列进行绑定
@Bean
public Binding bindingExchange1() {
return BindingBuilder.bind(queueFanout1()).to(exchangeFanout());
}
@Bean
public Binding bindingExchange2() {
return BindingBuilder.bind(queueFanout2()).to(exchangeFanout());
}
RabbitmqController.java
/**
* 发布订阅模式
*
* @return success
*/
@RequestMapping("/sendPublish")
public String sendPublish() {
rabbitmqService.sendPublish();
return "发送成功...";
}
IRabbitmqService.java
void sendPublish();
RabbitmqService.java
@Override
public void sendPublish() {
for (int i = 0; i < 5; i++) {
// 使用 convertSendAndReceive 方法时的结果:使用此方法,只有确定消费者接收到消息,才会发送下一条信息,每条消息之间会有间隔时间
// rabbitTemplate.convertSendAndReceive("exchange_fanout", "", "测试发布订阅模型:" + i);
//使用 convertAndSend 方法时的结果:输出时没有顺序,不需要等待,直接运行
rabbitTemplate.convertAndSend("exchange_fanout", "", "测试发布订阅模型:" + i);
}
}
PublishReceiveListener.java
@Component
@Slf4j
public class PublishReceiveListener {
@RabbitListener(queues = "queue_fanout1")
public void receiveMsg1(String msg) {
log.info("队列1接收到消息:{}" , msg);
}
@RabbitListener(queues = "queue_fanout2")
public void receiveMsg2(String msg) {
log.info("队列2接收到消息:{}" , msg);
}
}
测试发布订阅模型
http://localhost:8080/sendPublish
控制台打印
topic 模型
RabbitmqConfig.java
// topic 模型
@Bean
public Queue queueTopic1() {
return new Queue("queue_topic1");
}
@Bean
public Queue queueTopic2() {
return new Queue("queue_topic2");
}
@Bean
public TopicExchange exchangeTopic() {
return new TopicExchange("exchange_topic");
}
/**
* *(星号):可以(只能)匹配一个单词
* #(井号):可以匹配多个单词(或者零个)
*/
@Bean
public Binding bindingTopic1() {
//# 匹配多个
return BindingBuilder.bind(queueTopic1()).to(exchangeTopic()).with("topic.#");
}
@Bean
public Binding bindingTopic2() {
// * 匹配一个
return BindingBuilder.bind(queueTopic2()).to(exchangeTopic()).with("topic.*");
}
RabbitmqController.java
/**
* topic 模式
*
* @return success
*/
@RequestMapping("/sendTopic")
public String sendTopic() {
rabbitmqService.sendTopic();
return "发送成功...";
}
IRabbitmqService.java
void sendTopic();
RabbitmqService.java
@Override
public void sendTopic() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km.topic", "测试发布订阅模型:" + i);
} else {
rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km", "测试发布订阅模型:" + i);
}
}
}
TopicReceiveListener.java
@Component
@Slf4j
public class TopicReceiveListener {
@RabbitListener(queues = "queue_topic1")
public void receiveMsg1(String msg) {
log.info("消费者1接收到:{}" , msg);
}
@RabbitListener(queues = "queue_topic2")
public void receiveMsg2(String msg) {
log.info("消费者2接收到:{}" , msg);
}
}
测试topic模式
http://localhost:8080/sendTopic
控制台打印
可以看到消费者1可以接受所有的信息,消费者2只能接受奇数的消息
在绑定路由规则中
-(星号)*:可以(只能)匹配一个单词
-(井号)#:可以匹配多个单词(或者零个)
发送方confirm机制
application.properties
# 开启消息确认机制 confirm 异步
spring.rabbitmq.publisher-confirm-type=correlated
# 之前的旧版本 开启消息确认机制的方式
# spring.rabbitmq.publisher-confirms=true
RabbitmqConfig.java
// confirm 机制
@Bean
public Queue queueConfirm() {
return new Queue("queue_confirm");
}
RabbitmqController.java
/**
* 确认机制
*
* @return success
*/
@RequestMapping("/sendConfirm")
public String sendConfirm() {
rabbitmqService.sendConfirm();
return "发送成功...";
}
IRabbitmqService.java
void sendConfirm();
RabbitmqService.java
// 配置 confirm 机制
private final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
/**
* @param correlationData 消息相关的数据,一般用于获取 唯一标识 id
* @param b true 消息确认成功,false 失败
* @param s 确认失败的原因
*/
@Override
public void confirm(CorrelationData correlationData, boolean b, String s) {
if (b) {
log.info("confirm 消息确认成功...{}", correlationData.getId());
} else {
log.info("confirm 消息确认失败...{} cause: {}", correlationData.getId(), s);
}
}
};
@Override
public void sendConfirm() {
rabbitTemplate.convertAndSend("queue_confirm", new User(1, "km", "km123", new Date()), new CorrelationData("" + System.currentTimeMillis()));
rabbitTemplate.setConfirmCallback(confirmCallback);
}
ConfirmReceiveListener.java
@Component
@Slf4j
public class ConfirmReceiveListener {
@RabbitListener(queues = "queue_confirm")
public void receiveMsg(User user) {
log.info("接收到的消息为:{}", user);
}
}
测试发送方Confirm
http://localhost:8080/sendConfirm
控制台打印
消费者ack接收以及拒绝
application.properties
# 消息开启手动确认
spring.rabbitmq.listener.simple.acknowledge-mode=manual
RabbitmqConfig.java
// 测试消费者ack确认
@Bean
public Queue queueAck() {
return new Queue("queue_ack");
}
@Bean
public TopicExchange exchangeAck() {
return new TopicExchange("exchange_ack");
}
@Bean
public Binding bindingAck() {
return BindingBuilder.bind(queueAck()).to(exchangeAck()).with("topic.*");
}
RabbitmqController.java
/**
* 测试消费者ack
*
* @return success
*/
@RequestMapping("/sendNeedAck")
public String sendNeedAck() {
rabbitmqService.sendNeedAck();
return "发送成功...";
}
IRabbitmqService.java
void sendNeedAck();
RabbitmqService.java
@Override
public void sendNeedAck() {
rabbitTemplate.convertAndSend("exchange_ack","topic.ack","测试 消费者ack机制");
}
ConfirmAckListener.java
@Component
@Slf4j
public class ConfirmAckListener {
@RabbitListener(queues = "queue_ack")
public void receiveMessage(Object obj, Channel channel, Message message) {
// 包含所有的信息
try {
log.info("接收到消息:{}", obj);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
// ack 不确认 requeue 是否重新放入队列 multiple 是否批量处理
// channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
//nack 与 reject区别就是同时支持多个消息,可以nack该消费者先前接收未ack的所有消息。nack后的消息也会被自己消费到。
// channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
} catch (IOException e) {
e.printStackTrace();
}
}
测试消费者ack接收以及reject
http://127.0.0.1:8080/sendNeedAck
控制台打印
ack 确认
ack 不确认 及其 reject
nack 与 reject区别就是同时支持多个消息,可以nack该消费者先前接收未ack的所有消息。nack后的消息也会被自己消费到。所以控制台中会一直打印
return机制
RabbitmqConfig.java
// 测试return机制
@Bean
public Queue queueReturn() {
return new Queue("queue_return");
}
@Bean
public TopicExchange exchangeReturn() {
return new TopicExchange("exchange_return");
}
@Bean
public Binding bindingReturn() {
return BindingBuilder.bind(queueReturn()).to(exchangeReturn()).with("return.*");
}
RabbitmqController.java
/**
* 返回机制
*
* @return success
*/
@RequestMapping("/sendReturn")
public String sendReturn() {
rabbitmqService.sendReturn();
return "发送成功...";
}
IRabbitmqService.java
void sendReturn();
RabbitmqService.java
// 测试return机制
@Override
public void sendReturn() {
rabbitTemplate.setReturnCallback(returnCallback);
// rabbitTemplate.convertAndSend("exchange_return", "return.km.km", "测试 return 机制");
rabbitTemplate.convertAndSend("exchange_return", "return.km", "测试 return 机制");
}
ReturnReceiveListener.java
@Component
@Slf4j
public class ReturnReceiveListener {
@RabbitListener(queues = "queue_return")
public void receiveMsg(String msg) {
log.info("接收的消息为:{}" , msg);
}
}
测试return方式
sendReturn
http://127.0.0.1:8080/sendReturn
控制台打印
正确使用路由
错误使用路由
死信队列/延时队列
死信队列到期后,会将信息转到另外一个普通队列接收
RabbitmqConfig.java
// TTL 队列
@Bean
public Queue queueTTL() {
Map map = new HashMap<>(1);
map.put("x-message-ttl", 10000);
return new Queue("queue_ttl", true, false, false, map);
}
// 产生死信的队列
@Bean
public Queue queueDLX() {
Map map = new HashMap<>(4);
// 5秒后,消息自动变为死信
map.put("x-message-ttl", 5000);
map.put("x-dead-letter-exchange", "exchange_receive");
map.put("x-dead-letter-routing-key", "receive_key");
return new Queue("queue_dlx", true, false, false, map);
}
// 死信交换机
@Bean
public DirectExchange exchangeDLX() {
return new DirectExchange("exchange_dlx");
}
// 给死信队列绑定交换机
@Bean
public Binding bindingDLX() {
return BindingBuilder.bind(queueDLX()).to(exchangeDLX()).with("receive_key");
}
// 死信接收交换机
@Bean
public DirectExchange exchangeReceive() {
return new DirectExchange("exchange_receive");
}
// 接收死信的队列
@Bean
public Queue queueReceive() {
return new Queue("queue_receive");
}
// 将交换机与队列绑定
@Bean
public Binding bindingReceive() {
return BindingBuilder.bind(queueReceive()).to(exchangeReceive()).with("receive_key");
}
RabbitmqController.java
/**
* 测试死信队列
*
* @return success
*/
@RequestMapping("/sendDead")
public String sendDead() {
rabbitmqService.sendDead();
return "发送成功...";
}
IRabbitmqService.java
void sendDead();
RabbitmqService.java
@Override
public void sendDead() {
rabbitTemplate.convertAndSend("exchange_dlx", "receive_key","测试死信队列");
}
DeadReceiveListener.java
@Component
@Slf4j
public class DeadReceiveListener {
@RabbitListener(queues = "queue_receive")
public void receiveMsg(String msg) {
log.info("队列接收到消息:{}" , msg);
}
}
测试死信队列
http://127.0.0.1:8080/sendDead
控制台打印
可以看到控制台五秒后打印接收的消息
博文不易,欢迎点赞关注!❤
源码地址:rabbitmq: rabbitmq实战 (gitee.com)
参考文档:
- RabbitMQ中文文档 · RabbitMQ in Chinese (mr-ping.com)
- Spring Boot(八):RabbitMQ 详解 - 纯洁的微笑 - 博客园 (cnblogs.com)
- SpringBoot2.x整合RabbitMQ(完整版)_孔明的博客-CSDN博客