在IDEA中新建一個Maven工程,並新增 RabbitMQ Java client依賴
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.5.1</version>
</dependency>
</dependencies>
複製程式碼
新建Send.java檔案,先不要關心方法及每個引數的具體作用
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}
}
複製程式碼
新建Recv.java檔案
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages.");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
複製程式碼
啟動RabbitMQ Server
brew services start rabbitmq
複製程式碼
執行 Send.main(),控制檯輸出如下:
[x] Sent 'Hello World!'
複製程式碼
執行Recv.main(),控制檯輸出如下:
[*] Waiting for messages.
[x] Received 'Hello World!'
複製程式碼
簡單概念
RabbitMQ是一個訊息代理,負責接收和轉發訊息。
P代表訊息的傳送者(producer),比如上面的Send類。
C代表訊息的接收者(consumer),比如上面的Recv類。
中間紅色的圖片代表訊息佇列(message queue)。訊息佇列可以通過名稱標識,比如上面的"hello"。