RabbitMQ - 消費者應用程式



現在讓我們建立一個消費者應用程式,它將從 RabbitMQ 佇列接收訊息。

建立專案

使用 Eclipse,選擇檔案新建Maven 專案。勾選建立簡單專案(跳過原型選擇)並單擊下一步。

輸入詳細資訊,如下所示

  • groupId – com.tutorialspoint

  • artifactId – consumer

  • version – 0.0.1-SNAPSHOT

  • name – RabbitMQ Consumer

單擊完成按鈕,將建立一個新專案。

pom.xml

現在更新 pom.xml 的內容,以包括對 ActiveMQ 的依賴。

<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>consumer</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>RabbitMQ Consumer</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.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class Consumer {
   private static String QUEUE = "MyFirstQueue";

   public static void main(String[] args) throws IOException, TimeoutException {
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost("localhost");
      Connection connection = factory.newConnection();
      Channel channel = connection.createChannel();

      channel.queueDeclare(QUEUE, false, false, false, null);
      System.out.println("Waiting for messages. To exit press CTRL+C");

      DeliverCallback deliverCallback = (consumerTag, delivery) -> {
         String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
         System.out.println("Received '" + message + "'");
      };
      channel.basicConsume(QUEUE, true, deliverCallback, consumerTag -> { });
   }
}

消費者類建立一個連線,建立一個通道,建立一個佇列(如果不存在),然後從佇列接收訊息(如有),並且它將繼續輪詢佇列以查詢訊息。傳遞一個訊息後,它將由 basicConsume() 方法使用 deliverCallback 來處理。

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

廣告
© . All rights reserved.