Rabbitmq 简明教程

RabbitMQ - Publisher Application

现在,让我们创建一个将消息发送到 RabbitMQ Exchange 的发布程序应用程序。此交换将把消息传递给与交换绑定的队列。

Create Project

使用 Eclipse 选择 FileNew * → *Maven Project 。勾选 创建简单项目(跳过原型选择),然后单击下一步。

按照以下所示输入详细信息 −

  1. groupId − com.tutorialspoint

  2. artifactId − publisher

  3. version − 0.0.1-SNAPSHOT

  4. name − RabbitMQ Publisher

单击“完成”按钮,将创建新项目。

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>publisher</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>RabbitMQ Publisher</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 主题的发布程序类以将其广播到所有订阅者。

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 Publisher {
   private static final String EXCHANGE = "MyExchange";
   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.exchangeDeclare(EXCHANGE, "fanout");
         Scanner input = new Scanner(System.in);
         String message;
         do {
            System.out.println("Enter message: ");
            message = input.nextLine();
            channel.basicPublish(EXCHANGE, "", null, message.getBytes());
         } while (!message.equalsIgnoreCase("Quit"));
      }
   }
}

生成程序类创建一个连接,创建一个通道,声明一个交换,然后要求用户输入消息。消息被发送到交换,并且作为队列名称,我们没有传递队列名称,因此所有与该交换绑定的队列都将收到该消息。如果用户输入退出,则应用程序终止,否则它会将消息发送到主题。

我们将在 RabbitMQ - Test Application 一章中运行此应用程序。