#RabbitMQ消息可靠性(二)
上一篇文章我们介绍了如何确保RabbitMQ消息发送的可靠性。本节介绍消息消费的可靠性。
文章目录
一、推模式手动确认二、拉模式手动确认
一、推模式手动确认
spring:
rabbitmq:
virtual-host: /
host: 127.0.0.1
port: 5672
username: guest
password: guest
listener:
simple:
## 消息手动确认
acknowledge-mode: manual
@RabbitListener(queues = RabbitConfig.QUEUE_NAME)
public void listenMessage(Message message, Channel channel){
long deliveryTag = message.getMessageProperties().getDeliveryTag();
try {
byte[] body = message.getBody();
String s = new String(body);
logger.info("message=====> {}",s);
int i = 1/0;
// 仅确认当前消息
channel.basicAck(deliveryTag,false);
} catch (Exception e) {
try {
// 重新放入队列中
channel.basicNack(deliveryTag,false,true);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
二、拉模式手动确认
@Test
void contextLoads() {
long deliveryTag = 0;
Channel channel = rabbitTemplate.getConnectionFactory().createConnection().createChannel(false);
try {
GetResponse response = channel.basicGet(RabbitConfig.QUEUE_NAME, false);
deliveryTag = response.getEnvelope().getDeliveryTag();
byte[] body = response.getBody();
String s = new String(body);
System.out.println(s);
channel.basicAck(deliveryTag,false);
} catch (Exception e) {
try {
channel.basicNack(deliveryTag,false,true);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}



