wuyouming666
2024-05-11 7dfc5501decb84bce7fe0563956eae705844a2f2
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
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;
 
                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);
 
            }
        }
 
        // 打印所有消息内容
        for (String message : messages) {
            System.out.println("Received message: " + message);
        }
    }
}