RabbitMQ - 釋出程式



現在,讓我們建立一個釋出程式,它將訊息傳送到 RabbitMQ Exchange。此 Exchange 會將訊息傳遞給與其繫結的佇列。

建立專案

使用 Eclipse,選擇FileNew Maven Project。勾選Create a simple project(skip archetype selection) 選項,然後單擊 Next。

輸入詳細資訊,如下所示−

  • groupId − com.tutorialspoint

  • artifactId − publisher

  • version − 0.0.1-SNAPSHOT

  • name − RabbitMQ Publisher

點選 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>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"));
      }
   }
}

生產程式類會建立連線、建立頻道、宣告 Exchange,然後要求使用者輸入訊息。訊息被髮送到 Exchange,並且,由於沒有傳遞佇列名稱,因此所有繫結到此 Exchange 的佇列都將收到訊息。如果使用者輸入 quit,那麼程式將終止,否則,它將訊息傳送到主題。

我們將在RabbitMQ - 測試程式一章中執行此程式。

廣告
© . All rights reserved.