使用 Node.js 将事件发送到 Azure 事件中心或从其接收事件Send events to or receive events from Azure Event Hubs using Node.js

Azure 事件中心是一个大数据流式处理平台和事件引入服务,每秒能够接收和处理数百万个事件。Azure Event Hubs is a Big Data streaming platform and event ingestion service that can receive and process millions of events per second. 事件中心可以处理和存储分布式软件和设备生成的事件、数据或遥测。Event Hubs can process and store events, data, or telemetry produced by distributed software and devices. 可以使用任何实时分析提供程序或批处理/存储适配器转换和存储发送到数据中心的数据。Data sent to an event hub can be transformed and stored using any real-time analytics provider or batching/storage adapters. 有关事件中心的详细概述,请参阅事件中心概述事件中心功能For detailed overview of Event Hubs, see Event Hubs overview and Event Hubs features.

本教程介绍了如何创建 Node.js 应用程序来将事件发送到事件中心或从其接收事件。This tutorial describes how to create Node.js applications to send events to or receive events from an event hub.

Note

可以从 GitHub 下载此用作示例的快速入门,将 EventHubConnectionStringEventHubName 字符串替换为事件中心值,并运行它。You can download this quickstart as a sample from the GitHub, replace EventHubConnectionString and EventHubName strings with your event hub values, and run it. 或者,可以按照本教程中的步骤创建自己的解决方案。Alternatively, you can follow the steps in this tutorial to create your own.

先决条件Prerequisites

若要完成本教程,需要满足以下先决条件:To complete this tutorial, you need the following prerequisites:

  • 有效的 Azure 帐户。An active Azure account. 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.
  • Node.js 版本 8.x 和更高版本。Node.js version 8.x and higher. https://nodejs.org 下载最新的 LTS 版本。Download the latest LTS version from https://nodejs.org.
  • Visual Studio Code(推荐使用)或任何其他 IDEVisual Studio Code (recommended) or any other IDE
  • 创建事件中心命名空间和事件中心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 continue with the following steps in this tutorial. 然后,按照以下文章中的说明获取事件中心命名空间的连接字符串:获取连接字符串Then, get the connection string for the event hub namespace by following instructions from the article: Get connection string. 本教程后面的步骤将使用此连接字符串。You use the connection string later in this tutorial.

安装 npm 包Install npm package

若要安装事件中心的 npm 包,请打开路径中包含 npm 的命令提示符,将目录更改为要包含示例的文件夹,然后运行此命令To install the 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 have your samples and then run this command

npm install @azure/event-hubs

若要安装事件处理程序主机的 npm 包,请改为运行以下命令To install the npm package for Event Processor Host, run the below command instead

npm install @azure/event-processor-host

发送事件Send events

本部分展示了如何创建 Node.js 应用程序来将事件发送到事件中心。This section shows you how to create a Node.js 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 below code into it.
    const { EventHubClient } = require("@azure/event-hubs");
    
    // Define connection string and the name of the Event Hub
    const connectionString = "";
    const eventHubsName = "";
    
    async function main() {
      const client = EventHubClient.createFromConnectionString(connectionString, eventHubsName);
    
      for (let i = 0; i < 100; i++) {
        const eventData = {body: `Event ${i}`};
        console.log(`Sending message: ${eventData.body}`);
        await client.send(eventData);
      }
    
      await client.close();
    }
    
    main().catch(err => {
      console.log("Error occurred: ", err);
    });
    
  3. 在上面的代码中输入连接字符串和事件中心的名称Enter the connection string and the name of your Event Hub in the above code
  4. 然后在命令提示符下运行命令 node send.js 以执行此文件。Then run the command node send.js in a command prompt to execute this file. 这会向事件中心发送 100 个事件This will send 100 events to your Event Hub

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

接收事件Receive events

本部分介绍如何创建 Node.js 应用程序,该应用程序从事件中心的默认使用者组的单个分区接收事件。This section shows you how to create a Node.js application that receives events from a single partition of the default consumer group in an event hub.

  1. 打开你常用的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code.
  2. 创建一个名为 receive.js 的文件,并将下面的代码粘贴到其中。Create a file called receive.js and paste the below code into it.
    const { EventHubClient, delay } = require("@azure/event-hubs");
    
    // Define connection string and related Event Hubs entity name here
    const connectionString = "";
    const eventHubsName = "";
    
    async function main() {
      const client = EventHubClient.createFromConnectionString(connectionString, eventHubsName);
      const allPartitionIds = await client.getPartitionIds();
      const firstPartitionId = allPartitionIds[0];
    
      const receiveHandler = client.receive(firstPartitionId, eventData => {
        console.log(`Received message: ${eventData.body} from partition ${firstPartitionId}`);
      }, error => {
        console.log('Error when receiving message: ', error)
      });
    
      // Sleep for a while before stopping the receive operation.
      await delay(15000);
      await receiveHandler.stop();
    
      await client.close();
    }
    
    main().catch(err => {
      console.log("Error occurred: ", err);
    });
    
  3. 在上面的代码中输入连接字符串和事件中心的名称。Enter the connection string and the name of your Event Hub in the above code.
  4. 然后在命令提示符下运行命令 node receive.js 以执行此文件。Then run the command node receive.js in a command prompt to execute this file. 这将从事件中心的默认使用者组的分区之一接收事件This will receive events from one of the partitions of the default consumer group in your Event Hub

祝贺!Congratulations! 现在已从事件中心接收事件。You have now received events from event hub.

使用事件处理程序主机接收事件Receive events using Event Processor Host

本部分展示了如何在 Node.js 应用程序中使用 Azure EventProcessorHost 从事件中心接收事件。This section shows how to receive events from an event hub by using Azure EventProcessorHost in a Node.js application. EventProcessorHost (EPH) 通过在事件中心的使用者组中的所有分区中创建接收器,帮助你高效地从事件中心接收事件。The EventProcessorHost (EPH) helps you efficiently receive events from an event hub by creating receivers across all partitions in the consumer group of an event hub. 它定期在 Azure 存储 Blob 中为收到的消息的元数据创建检查点。It checkpoints metadata on received messages at regular intervals in an Azure Storage Blob. 使用此方式,可以很容易地在以后的某个时间从离开的位置继续接收消息。This approach makes it easy to continue receiving messages from where you left off at a later time.

  1. 打开你常用的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code.
  2. 创建一个名为 receiveAll.js 的文件,并将下面的代码粘贴到其中。Create a file called receiveAll.js and paste the below code into it.
    const { EventProcessorHost, delay } = require("@azure/event-processor-host");
    
    // Define connection string and related Event Hubs entity name here
    const eventHubConnectionString = "";
    const eventHubName = "";
    const storageConnectionString = "";
    
    async function main() {
      const eph = EventProcessorHost.createFromConnectionString(
        "my-eph",
        storageConnectionString,
        "my-storage-container-name",
        eventHubConnectionString,
        {
          eventHubPath: eventHubName,
          onEphError: (error) => {
            console.log("[%s] Error: %O", error);
          }
        }
      );
    
    
      eph.start((context, eventData) => {
        console.log(`Received message: ${eventData.body} from partition ${context.partitionId}`);
      }, error => {
        console.log('Error when receiving message: ', error)
      });
    
      // Sleep for a while before stopping the receive operation.
      await delay(15000);
      await eph.stop();
    }
    
    main().catch(err => {
      console.log("Error occurred: ", err);
    });
    
    
  3. 在上面的代码中输入连接字符串和事件中心的名称以及 Azure Blob 存储的连接字符串Enter the connection string and the name of your Event Hub in the above code along with connection string for an Azure Blob Storage
  4. 然后在命令提示符下运行命令 node receiveAll.js 以执行此文件。Then run the command node receiveAll.js in a command prompt to execute this file.

祝贺!Congratulations! 现在已使用事件处理程序主机从事件中心接收事件。You have now received events from event hub using Event Processor Host. 这将从事件中心的默认使用者组的所有分区接收事件This will receive events from all the partitions of the default consumer group in your Event Hub

后续步骤Next steps

请阅读以下文章:Read the following articles: