package com.example.springboot.component;
|
|
import com.rabbitmq.client.*;
|
|
import java.io.IOException;
|
import java.util.ArrayList;
|
import java.util.List;
|
|
public class MessageQueueReader {
|
|
private static final String QUEUE_NAME = "hangzhoumes";
|
|
public static void main(String[] args) throws Exception {
|
ConnectionFactory factory = new ConnectionFactory();
|
factory.setHost("localhost");
|
|
List<String> messages = new ArrayList<>();
|
|
try (Connection connection = factory.newConnection();
|
Channel channel = connection.createChannel()) {
|
boolean autoAck = false;
|
// autoAck 参数设置为 false,然后手动确认消息处理完成
|
// 循环获取队列中的所有消息
|
// while (true) {
|
GetResponse response = channel.basicGet(QUEUE_NAME, autoAck);
|
|
if (response != null) {
|
String message = new String(response.getBody(), "UTF-8");
|
messages.add(message);
|
|
// 手动确认消息处理完成
|
long deliveryTag = response.getEnvelope().getDeliveryTag();
|
channel.basicAck(deliveryTag, false);
|
// } else {
|
// // 如果队列为空,则退出循环
|
// break;
|
// }
|
}
|
}
|
|
// 打印所有消息内容
|
for (String message : messages) {
|
System.out.println("Received message: " + message);
|
}
|
}
|
}
|
|