guoyujie
2 天以前 c4b9a339caff12e95f61c3d5dc950aafcc8c566c
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.example.erp.common;
 
import com.rabbitmq.client.*;
 
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
 
public class RabbitMQUtil {
 
    private static final String SEND_QUEUE_NAME = "temperingUsed";
    private static final String RECEIVE_QUEUE_NAME = "temperingReturn";
    private static final String HOST = "localhost";
    private static final String USERNAME = "guest";
    private static final String PASSWORD = "guest";
 
    private ConnectionFactory factory;
    private Connection connection;
    private Channel sendChannel;
    private Channel receiveChannel;
    private BlockingQueue<String> messageQueue;
 
    public RabbitMQUtil() throws IOException, TimeoutException {
        factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
        connection = factory.newConnection();
 
        sendChannel = connection.createChannel();
        sendChannel.queueDeclare(SEND_QUEUE_NAME, false, false, false, null);
 
        receiveChannel = connection.createChannel();
        receiveChannel.queueDeclare(RECEIVE_QUEUE_NAME, false, false, false, null);
 
        messageQueue = new ArrayBlockingQueue<>(100); // 设置队列大小
        startConsuming();
    }
 
    public void sendMessage(String message) throws IOException {
        sendChannel.basicPublish("", SEND_QUEUE_NAME, null, message.getBytes());
    }
 
    public String receiveMessages() throws InterruptedException {
        return messageQueue.take(); // 阻塞直到有消息可用
    }
 
    private void startConsuming() throws IOException {
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            messageQueue.offer(message); // 将消息放入队列
        };
        receiveChannel.basicConsume(RECEIVE_QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }
 
    public void close() throws IOException, TimeoutException {
        if (sendChannel != null) {
            sendChannel.close();
        }
        if (receiveChannel != null) {
            receiveChannel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}