| | |
| | | import com.rabbitmq.client.*;
|
| | | import com.fasterxml.jackson.databind.ObjectMapper;
|
| | |
|
| | | import java.util.ArrayList;
|
| | | import java.util.List;
|
| | |
|
| | | public class RabbitMQUtils {
|
| | | // ObjectMapper对象,用于序列化和反序列化JSON
|
| | | private static ObjectMapper objectMapper = new ObjectMapper();
|
| | |
| | | }
|
| | | }
|
| | |
|
| | |
|
| | | public List<String> readMessages(String queueName) 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;
|
| | |
|
| | | GetResponse response = channel.basicGet(queueName, autoAck);
|
| | | if (response != null) {
|
| | | String message = new String(response.getBody(), "UTF-8");
|
| | | messages.add(message);
|
| | | // 手动确认消息处理完成
|
| | | long deliveryTag = response.getEnvelope().getDeliveryTag();
|
| | | channel.basicAck(deliveryTag, false);
|
| | | }
|
| | | }
|
| | |
|
| | | return messages;
|
| | | }
|
| | |
|
| | | // 从 RabbitMQ 队列中接收消息
|
| | | public static void receiveMessage(String queueName) throws Exception {
|
| | | // 创建连接工厂并设置主机名
|