Skip to content

Commit 84146c1

Browse files
author
yanpenglei
committed
SpringBoot集成RabbitMQ消息队列ACK消息确认
1 parent 509ca4b commit 84146c1

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

spring-boot-rabbitmq-ack/src/main/java/com/souyunku/example/springboot/rabbitmq/ack/config/RabbitConfig.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ public class RabbitConfig {
99

1010
@Bean
1111
public Queue QueueA() {
12-
return new Queue("hello");
12+
// boolean durable = true 持久化
13+
return new Queue("hello", true);
1314
}
1415

1516
}

spring-boot-rabbitmq-ack/src/main/java/com/souyunku/example/springboot/rabbitmq/ack/producer/HelloSender.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@ public class HelloSender implements RabbitTemplate.ReturnCallback {
1616
public void sendMessage(String context) {
1717
System.out.println("HelloReceiver发送内容: " + context + ",发送时间:" + new Date());
1818

19+
20+
// 消息发送失败返回到队列中, application.properties 配置 spring.rabbitmq.publisher-returns=true
21+
rabbitTemplate.setMandatory(true);
22+
1923
this.rabbitTemplate.setReturnCallback(this);
24+
2025
this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
2126
if (!ack) {
2227
System.out.println("sendMessage 发送失败" + cause + correlationData.toString());

spring-boot-rabbitmq-ack/src/main/java/com/souyunku/example/springboot/rabbitmq/ack/receiver/HelloReceiver.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,18 @@ public void process(String context, Message message, Channel channel) throws Exc
2020
System.out.println("HelloReceiver收到内容: " + context + ",收到时间:" + new Date());
2121
try {
2222
//告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
23-
//channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
23+
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
24+
//消息确认 因为我在属性配置文件里面开启了ACK确认 所以如果代码没有执行ACK确认 你在RabbitMQ的后台会看到消息会一直留在队列里面未消费掉 只要程序一启动开始接受该队列消息的时候 又会收到
25+
2426
System.out.println("HelloReceiver消息接收成功");
2527
} catch (Exception e) {
2628
e.printStackTrace();
27-
//丢弃这条消息
29+
///ack返回false,并重新回到队列,api里面解释得很清楚
2830
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
2931
System.out.println("消息接收失败");
3032
}
3133

3234
}
3335

36+
3437
}

0 commit comments

Comments
 (0)