严智鑫
2024-03-18 331e7fc1b8f332ccecb8e9af59a826d6ae80ba10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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);
        }
    }
}