Rabbitmq 简明教程
RabbitMQ - Producer Application
现在,我们创建一个生产者应用程序,它将向 RabbitMQ 队列发送消息。
Now let’s create a producer application which will send message to the RabbitMQ Queue.
Create Project
使用 Eclipse 选择 File → New * → *Maven Project 。勾选 创建简单项目(跳过原型选择),然后单击下一步。
Using eclipse, select File → New * → *Maven Project. Tick the *Create a simple project(skip archetype selection) * and click Next.
按照以下所示输入详细信息 −
Enter the details, as shown below −
-
groupId − com.tutorialspoint
-
artifactId − producer
-
version − 0.0.1-SNAPSHOT
-
name − RabbitMQ Producer
单击“完成”按钮,将创建新项目。
Click on Finish button and a new project will be created.
pom.xml
现在更新 pom.xml 的内容以包含 RabbitMQ 的依赖项。
Now update the content of pom.xml to include dependencies for 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>
现在创建一个生产者类,它将向 RabbitMQ 队列发送消息。
Now create a Producer class which will send message to the RabbitMQ Queue.
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"));
}
}
}
生产者类创建一个连接,创建一个通道,连接到一个队列。如果用户输入“退出”,则应用程序终止,否则它将使用 basicPublish 方法向队列发送消息。
Producer class creates a connection, creates a channel, connects to a queue. If user enters quit then application terminates else it will send the message to the queue using basicPublish method.
我们在 RabbitMQ - Test Application 章节中运行此应用程序。
We’ll run this application in RabbitMQ - Test Application chapter.