- RabbitMQ 教程
- RabbitMQ——主頁
- RabbitMQ——概述
- RabbitMQ——環境設定
- RabbitMQ——特性
- RabbitMQ——安裝
- 基於佇列的示例
- RabbitMQ——生產者應用程式
- RabbitMQ——消費者應用程式
- RabbitMQ——測試應用程式
- 基於主題的示例
- RabbitMQ——釋出者應用程式
- RabbitMQ——訂閱者應用程式
- RabbitMQ——測試應用程式
- RabbitMQ 有用資源
- RabbitMQ——快速指南
- RabbitMQ——有用資源
- RabbitMQ——討論
RabbitMQ——生產者應用程式
現在,讓我們建立一個生產者應用程式,它會向 RabbitMQ 佇列傳送訊息。
建立專案
使用 Eclipse,選擇 **File → New → Maven Project**。勾選 **Create a simple project (skip archetype selection)**,然後單擊 Next。
輸入詳細資訊,如下所示 −
**groupId** − com.tutorialspoint
**artifactId** − producer
**version** − 0.0.1-SNAPSHOT
**name** − RabbitMQ Producer
單擊 Finish 按鈕,將會建立一個新專案。
pom.xml
現在,更新 pom.xml 的內容,將其包含為 RabbitMQ 的依賴關係。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.activemq</groupId>
<artifactId>producer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RabbitMQ Producer</name>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.14.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.26</version>
</dependency>
</dependencies>
</project>
現在建立一個 Production 類,它會向 RabbitMQ 佇列傳送訊息。
package com.tutorialspoint.rabbitmq;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Producer {
private static String QUEUE = "MyFirstQueue";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE, false, false, false, null);
Scanner input = new Scanner(System.in);
String message;
do {
System.out.println("Enter message: ");
message = input.nextLine();
channel.basicPublish("", QUEUE, null, message.getBytes());
} while (!message.equalsIgnoreCase("Quit"));
}
}
}
Production 類建立一個連線,建立一個通道並連線到佇列。如果使用者輸入 quit,則應用程式終止,否則它將使用 basicPublish 方法向佇列傳送訊息。
我們將在 RabbitMQ - 測試應用程式 一章中執行該應用程式。
廣告