使用 JavaScript(azure/event-hubs 版本 5)向/从事件中心发送/接收事件Send events to or receive events from event hubs by using JavaScript (azure/event-hubs version 5)

本快速入门介绍如何使用 azure/event-hubs 版本 5 JavaScript 包向事件中心发送事件以及从事件中心接收事件。This quickstart shows how to send events to and receive events from an event hub using the azure/event-hubs version 5 JavaScript package.

重要

本快速入门使用最新的 azure/event-hubs 版本 5 包。This quickstart uses the latest azure/event-hubs version 5 package. 有关使用旧的 azure/event-hubs 版本 2 包的快速入门,请参阅使用 azure/event-hubs 版本 2 发送和接收事件For a quick start that uses the old azure/event-hubs version 2 package, see Send and receive events using azure/event-hubs version 2.

先决条件Prerequisites

如果不熟悉 Azure 事件中心,请在阅读本快速入门之前参阅事件中心概述If you are new to Azure Event Hubs, see Event Hubs overview before you do this quickstart.

若要完成本快速入门,需要具备以下先决条件:To complete this quickstart, you need the following prerequisites:

  • Azure 订阅Azure subscription. 若要使用 Azure 服务(包括 Azure 事件中心),需要一个订阅。To use Azure services, including Azure Event Hubs, you need a subscription. 如果没有现有 Azure 帐户,可以注册 1 元试用版创建帐户If you don't have an existing Azure account, you can sign up for a 1mb trial or create an account.

  • Node.js 版本 8.x 或更高版本。Node.js version 8.x or later. 下载最新的长期支持 (LTS) 版本Download the latest long-term support (LTS) version.

  • Visual Studio Code(推荐)或任何其他集成开发环境 (IDE)。Visual Studio Code (recommended) or any other integrated development environment (IDE).

  • 有效的事件中心命名空间和事件中心。An active Event Hubs namespace and event hub. 若要创建它们,请执行以下步骤:To create them, do the following steps:

    1. Azure 门户中,创建“事件中心”类型的命名空间,然后获取应用程序与事件中心进行通信所需的管理凭据。 In the Azure portal, create a namespace of type Event Hubs, and then obtain the management credentials that your application needs to communicate with the event hub.
    2. 若要创建命名空间和事件中心,请按照以下文章中的说明操作:快速入门:使用 Azure 门户创建事件中心To create the namespace and event hub, follow the instructions at Quickstart: Create an event hub by using the Azure portal.
    3. 按照本快速入门中的说明继续操作。Continue by following the instructions in this quickstart.
    4. 若要获取事件中心命名空间的连接字符串,请按照获取连接字符串 中的说明操作。To get the connection string for your Event Hub namespace, follow the instructions in Get connection string. 请记下该连接字符串,以便稍后在本快速入门中使用。Record the connection string to use later in this quickstart.
  • 创建事件中心命名空间和事件中心Create an Event Hubs namespace and an event hub. 第一步是使用 Azure 门户创建事件中心类型的命名空间,并获取应用程序与事件中心进行通信所需的管理凭据。The first step is to use the Azure portal to create a namespace of type Event Hubs, and obtain the management credentials your application needs to communicate with the event hub. 要创建命名空间和事件中心,请按照此文中的步骤操作。To create a namespace and an event hub, follow the procedure in this article. 然后,按照以下文章中的说明获取事件中心命名空间的连接字符串获取连接字符串Then, get the connection string for the Event Hubs namespace by following instructions from the article: Get connection string. 稍后将在本快速入门中使用连接字符串。You use the connection string later in this quickstart.

安装 npm 包Install the npm package

若要安装适用于事件中心的 Node 包管理器 (npm) 包,请打开路径中包含 npm 的命令提示符,将目录切换到用于保存示例的文件夹,然后运行以下命令:To install the Node Package Manager (npm) package for Event Hubs, open a command prompt that has npm in its path, change the directory to the folder where you want to keep your samples, and then run this command:

npm install @azure/event-hubs

对于接收端,需要额外安装两个包。For the receiving side, you need to install two more packages. 本快速入门将使用 Azure Blob 存储来保存检查点,使程序不会读取已读取的事件。In this quickstart, you use Azure Blob storage to persist checkpoints so that the program doesn't read the events that it has already read. 它在 Blob 中按固定的时间间隔对收到的消息执行元数据检查点。It performs metadata checkpoints on received messages at regular intervals in a blob. 使用此方式可以很容易地在以后的某个时间从退出的位置继续接收消息。This approach makes it easy to continue receiving messages later from where you left off.

运行以下命令:Run the following commands:

npm install @azure/storage-blob
npm install @azure/eventhubs-checkpointstore-blob

发送事件Send events

在本部分中,你将创建一个可向事件中心发送事件的 JavaScript 应用程序。In this section, you create a JavaScript application that sends events to an event hub.

  1. 打开你常用的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code.

  2. 创建名为 send.js 的文件,然后将以下代码粘贴到其中:Create a file called send.js, and paste the following code into it:

    const { EventHubProducerClient } = require("@azure/event-hubs");
    
    const connectionString = "EVENT HUBS NAMESPACE CONNECTION STRING";
    const eventHubName = "EVENT HUB NAME";
    
    async function main() {
    
      // Create a producer client to send messages to the event hub.
      const producer = new EventHubProducerClient(connectionString, eventHubName);
    
      // Prepare a batch of three events.
      const batch = await producer.createBatch();
      batch.tryAdd({ body: "First event" });
      batch.tryAdd({ body: "Second event" });
      batch.tryAdd({ body: "Third event" });    
    
      // Send the batch to the event hub.
      await producer.sendBatch(batch);
    
      // Close the producer client.
      await producer.close();
    
      console.log("A batch of three events have been sent to the event hub");
    }
    
    main().catch((err) => {
      console.log("Error occurred: ", err);
    });
    
  3. 在代码中,使用实际值替换以下内容:In the code, use real values to replace the following:

    • EVENT HUBS NAMESPACE CONNECTION STRING
    • EVENT HUB NAME
  4. 运行 node send.js 以执行此文件。Run node send.js to execute this file. 此命令将包含三个事件的批发送到事件中心。This command sends a batch of three events to your event hub.

  5. 在 Azure 门户中,验证事件中心是否已收到消息。In the Azure portal, verify that the event hub has received the messages. 在“指标”部分切换到“消息”视图。 In the Metrics section, switch to Messages view. 刷新页面以更新图表。Refresh the page to update the chart. 可能需要在几秒钟后才会显示已收到消息。It might take a few seconds for it to show that the messages have been received.

    验证事件中心是否已收到消息Verify that the event hub received the messages

    备注

    有关完整源代码(包括附加的参考注释),请参阅 GitHub sendEvents.js 页For the complete source code, including additional informational comments, go to the GitHub sendEvents.js page.

祝贺!Congratulations! 现在已向事件中心发送事件。You have now sent events to an event hub.

接收事件Receive events

在本部分中,你将在 JavaScript 应用程序中使用 Azure Blob 存储检查点存储从事件中心接收事件。In this section, you receive events from an event hub by using an Azure Blob storage checkpoint store in a JavaScript application. 该应用程序将在 Azure 存储 Blob 中定期针对收到的消息执行元数据检查点。It performs metadata checkpoints on received messages at regular intervals in an Azure Storage blob. 使用此方式可以很容易地在以后的某个时间从退出的位置继续接收消息。This approach makes it easy to continue receiving messages later from where you left off.

备注

如果在 Azure Stack Hub 上运行,该平台支持的存储 Blob SDK 版本可能不同于通常在 Azure 上提供的版本。If you are running on Azure Stack Hub, that platform may support a different version of Storage Blob SDK than those typically available on Azure. 例如,如果在 Azure Stack Hub 版本 2002 上运行,则存储服务的最高可用版本为版本 2017-11-09。For example, if you are running on Azure Stack Hub version 2002, the highest available version for the Storage service is version 2017-11-09. 在这种情况下,除了执行本部分中的步骤以外,还需要添加相关代码,将存储服务 API 版本 2017-11-09 作为目标。In this case, besides following steps in this section, you will also need to add code to target the Storage service API version 2017-11-09. 如需通过示例来了解如何以特定的存储 API 版本为目标,请参阅 GitHub 上的此示例For an example on how to target a specific Storage API version, see this sample on GitHub. 有关 Azure Stack Hub 上支持的 Azure 存储服务版本的详细信息,请参阅 Azure Stack Hub 存储:差异和注意事项For more information on the Azure Storage service versions supported on Azure Stack Hub, please refer to Azure Stack Hub storage: Differences and considerations.

创建 Azure 存储帐户和 Blob 容器Create an Azure storage account and a blob container

若要创建 Azure 存储帐户并在其中创建 Blob 容器,请执行以下操作:To create an Azure storage account and a blob container in it, do the following actions:

  1. 创建 Azure 存储帐户Create an Azure storage account
  2. 在存储帐户中创建 Blob 容器Create a blob container in the storage account
  3. 获取存储帐户的连接字符串Get the connection string to the storage account

请务必记下连接字符串和容器名称,供稍后在接收代码中使用。Be sure to record the connection string and container name for later use in the receive code.

编写用于接收事件的代码Write code to receive events

  1. 打开偏好的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code.

  2. 创建名为 receive.js 的文件,然后将以下代码粘贴到其中:Create a file called receive.js, and paste the following code into it:

    const { EventHubConsumerClient } = require("@azure/event-hubs");
    const { ContainerClient } = require("@azure/storage-blob");    
    const { BlobCheckpointStore } = require("@azure/eventhubs-checkpointstore-blob");
    
    const connectionString = "EVENT HUBS NAMESPACE CONNECTION STRING";    
    const eventHubName = "EVENT HUB NAME";
    const consumerGroup = "$Default"; // name of the default consumer group
    const storageConnectionString = "AZURE STORAGE CONNECTION STRING";
    const containerName = "BLOB CONTAINER NAME";
    
    async function main() {
      // Create a blob container client and a blob checkpoint store using the client.
      const containerClient = new ContainerClient(storageConnectionString, containerName);
      const checkpointStore = new BlobCheckpointStore(containerClient);
    
      // Create a consumer client for the event hub by specifying the checkpoint store.
      const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName, checkpointStore);
    
      // Subscribe to the events, and specify handlers for processing the events and errors.
      const subscription = consumerClient.subscribe({
          processEvents: async (events, context) => {
            for (const event of events) {
              console.log(`Received event: '${event.body}' from partition: '${context.partitionId}' and consumer group: '${context.consumerGroup}'`);
            }
            // Update the checkpoint.
            await context.updateCheckpoint(events[events.length - 1]);
          },
    
          processError: async (err, context) => {
            console.log(`Error : ${err}`);
          }
        }
      );
    
      // After 30 seconds, stop processing.
      await new Promise((resolve) => {
        setTimeout(async () => {
          await subscription.close();
          await consumerClient.close();
          resolve();
        }, 30000);
      });
    }
    
    main().catch((err) => {
      console.log("Error occurred: ", err);
    });    
    
  3. 在代码中,使用实际值替换以下值:In the code, use real values to replace the following values:

    • EVENT HUBS NAMESPACE CONNECTION STRING
    • EVENT HUB NAME
    • AZURE STORAGE CONNECTION STRING
    • BLOB CONTAINER NAME
  4. 在命令提示符下运行 node receive.js 以执行此文件。Run node receive.js in a command prompt to execute this file. 窗口中应会显示有关已收到事件的消息。The window should display messages about received events.

    备注

    有关完整源代码(包括附加的参考注释),请参阅 GitHub receiveEventsUsingCheckpointStore.js 页For the complete source code, including additional informational comments, go to the GitHub receiveEventsUsingCheckpointStore.js page.

祝贺你!Congratulations! 现已从事件中心收到事件。You have now received events from your event hub. 接收器程序将从事件中心内默认使用者组的所有分区接收事件。The receiver program will receive events from all the partitions of the default consumer group in the event hub.

后续步骤Next steps

查看 GitHub 中的以下示例:Check out these samples on GitHub: