向/从 Azure 事件中心发送/接收事件 - .NET Core (Azure.Messaging.EventHubs)Send events to and receive events from Azure Event Hubs - .NET Core (Azure.Messaging.EventHubs)

本快速入门介绍如何使用 Azure.Messaging.EventHubs .NET Core 库向事件中心发送事件以及从事件中心接收事件。This quickstart shows how to send events to and receive events from an event hub using the Azure.Messaging.EventHubs .NET Core library.

Important

本快速入门使用新的 Azure.Messaging.EventHubs 库。This quickstart uses the new Azure.Messaging.EventHubs library. 有关使用旧的 Microsoft.Azure.EventHubs 库的快速入门,请参阅使用 Microsoft.Azure.EventHubs 库发送和接收事件For a quickstart that uses the old Microsoft.Azure.EventHubs library, see Send and receive events using Microsoft.Azure.EventHubs library.

先决条件Prerequisites

如果不熟悉 Azure 事件中心,请在阅读本快速入门之前参阅事件中心概述If you're 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.
  • Microsoft Visual Studio 2019Microsoft Visual Studio 2019. Azure 事件中心客户端库利用 C# 8.0 中引入的新功能。The Azure Event Hubs client library makes use of new features that were introduced in C# 8.0. 仍可以在旧版 C# 中使用该库,但该库的某些功能不可用。You can still use the library with older versions of C#, but some of its functionality won't be available. 若要启用这些功能,必须将 .NET Core 3.0 用作目标,或指定要使用的语言版本(8.0 或更高)。To enable these features, you must target .NET Core 3.0 or specify the language version you want to use (8.0 or above). 如果使用 Visual Studio,Visual Studio 2019 以前的版本与用于生成 C# 8.0 项目的工具将不兼容。If you're using Visual Studio, versions prior to Visual Studio 2019 aren't compatible with the tools needed to build C# 8.0 projects. 可在此处下载 Visual Studio 2019(包括免费的 Community Edition)Visual Studio 2019, including the free Community edition, can be downloaded here
  • 创建事件中心命名空间和事件中心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 tutorial.

发送事件Send events

此部分介绍如何创建可将事件发送到事件中心的 .NET Core 控制台应用程序。This section shows you how to create a .NET Core console application to send events to an event hub.

创建控制台应用程序Create a console application

  1. 启动 Visual Studio 2019。Start Visual Studio 2019.

  2. 选择“创建新项目”。 Select Create a new project.

  3. 在“创建新项目”对话框中执行以下步骤: 如果看不到此对话框,请在菜单中选择“文件”,然后依次选择“新建”、“项目”。 On the Create a new project dialog box, do the following steps: If you don't see this dialog box, select File on the menu, select New, and then select Project.

    1. 选择“C#”作为编程语言。 Select C# for the programming language.

    2. 选择“控制台”作为应用程序类型。 Select Console for the type of the application.

    3. 从结果列表中选择“控制台应用(.NET Core)”。 Select Console App (.NET Core) from the results list.

    4. 然后,选择“下一步” 。Then, select Next.

      “新建项目”对话框

  4. 输入 EventHubsSender 作为项目名称,输入 EventHubsQuickStart 作为解决方案名称,然后选择“确定”以创建项目。 Enter EventHubsSender for the project name, EventHubsQuickStart for the solution name, and then select OK to create the project.

    C# > 控制台应用

添加事件中心 NuGet 包Add the Event Hubs NuGet package

  1. 在菜单中选择“工具” > “NuGet 包管理器” > “包管理器控制台” 。Select Tools > NuGet Package Manager > Package Manager Console from the menu.

  2. 运行以下命令安装 Azure.Messaging.EventHubs NuGet 包:Run the following command to install the Azure.Messaging.EventHubs NuGet package:

    Install-Package Azure.Messaging.EventHubs
    

编写代码以将消息发送到事件中心Write code to send messages to the event hub

  1. Program.cs 文件顶部添加以下 using 语句:Add the following using statements to the top of the Program.cs file:

    using System.Text;
    using System.Threading.Tasks;
    using Azure.Messaging.EventHubs;
    using Azure.Messaging.EventHubs.Producer;
    
  2. 将事件中心连接字符串和事件中心名称的常量添加到 Program 类。Add constants to the Program class for the Event Hubs connection string and the event hub name. 请将括号中的占位符替换为在创建事件中心时获取的适当值。Replace placeholders in brackets with the proper values that you got when creating the event hub. 请确保 {Event Hubs namespace connection string} 是命名空间级别的连接字符串,而不是事件中心字符串。Make sure that the {Event Hubs namespace connection string} is the namespace-level connection string, and not the event hub string.

    private const string connectionString = "<EVENT HUBS NAMESPACE - CONNECTION STRING>";
    private const string eventHubName = "<EVENT HUB NAME>";
    
  3. Main 方法替换为以下 async Main 方法。Replace the Main method with the following async Main method. 参阅代码注释了解详细信息。See the code comments for details.

        static async Task Main()
        {
            // Create a producer client that you can use to send events to an event hub
            await using (var producerClient = new EventHubProducerClient(connectionString, eventHubName))
            {
                // Create a batch of events 
                using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
    
                // Add events to the batch. An event is a represented by a collection of bytes and metadata. 
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("First event")));
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Second event")));
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Third event")));
    
                // Use the producer client to send the batch of events to the event hub
                await producerClient.SendAsync(eventBatch);
                Console.WriteLine("A batch of 3 events has been published.");
            }
        }
    
  4. 生成项目并确保没有错误。Build the project, and ensure that there are no errors.

  5. 运行程序并等待出现确认消息。Run the program and wait for the confirmation message.

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

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

    Note

    有关包含更详细注释的完整源代码,请参阅 GitHub 上的此文件For the complete source code with more informational comments, see this file on the GitHub

接收事件Receive events

本部分介绍如何编写一个使用事件处理器从事件中心接收消息的 .NET Core 控制台应用程序。This section shows how to write a .NET Core console application that receives messages from an event hub using an event processor. 该事件处理器通过从事件中心管理持久检查点和并行接收操作,来简化从这些事件中心接收事件的过程。The event processor simplifies receiving events from event hubs by managing persistent checkpoints and parallel receives from those event hubs. 事件处理器与特定的事件中心和使用者组相关联。An event processor is associated with a specific event Hub and a consumer group. 它从事件中心内的多个分区接收事件,并将其传递给处理程序委托,以使用提供的代码进行处理。It receives events from multiple partitions in the event hub, passing them to a handler delegate for processing using code that you provide.

Note

如果在 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 and a blob container

本快速入门使用 Azure 存储作为检查点存储。In this quickstart, you use Azure Storage as the checkpoint store. 按照以下步骤创建 Azure 存储帐户。Follow these steps to create an Azure Storage account.

  1. 创建 Azure 存储帐户Create an Azure Storage account

  2. 创建一个 blob 容器Create a blob container

  3. 获取存储帐户的连接字符串Get the connection string to the storage account

    请记下该连接字符串和容器名称。Note down the connection string and the container name. 稍后要在接收代码中使用这些信息。You'll use them in the receive code.

为接收器创建项目Create a project for the receiver

  1. 在“解决方案资源管理器”窗口中,右键单击“EventHubQuickStart”解决方案,指向“添加”,然后选择“新建项目”。 In the Solution Explorer window, right-click the EventHubQuickStart solution, point to Add, and select New Project.
  2. 依次选择“控制台应用(.NET Core)”、“下一步”。 Select Console App (.NET Core), and select Next.
  3. 输入 EventHubsReceiver 作为项目名称,然后选择“创建”。 Enter EventHubsReceiver for the Project name, and select Create.

添加事件中心 NuGet 包Add the Event Hubs NuGet package

  1. 在菜单中选择“工具” > “NuGet 包管理器” > “包管理器控制台” 。Select Tools > NuGet Package Manager > Package Manager Console from the menu.

  2. 运行以下命令安装 Azure.Messaging.EventHubs NuGet 包:Run the following command to install the Azure.Messaging.EventHubs NuGet package:

    Install-Package Azure.Messaging.EventHubs
    
  3. 运行以下命令安装 Azure.Messaging.EventHubs.Processor NuGet 包:Run the following command to install the Azure.Messaging.EventHubs.Processor NuGet package:

    Install-Package Azure.Messaging.EventHubs.Processor
    

更新 Main 方法Update the Main method

  1. Program.cs 文件顶部添加以下 using 语句。Add the following using statements at the top of the Program.cs file.

    using System.Text;
    using System.Threading.Tasks;
    using Azure.Storage.Blobs;
    using Azure.Messaging.EventHubs;
    using Azure.Messaging.EventHubs.Consumer;
    using Azure.Messaging.EventHubs.Processor;
    
  2. 将事件中心连接字符串和事件中心名称的常量添加到 Program 类。Add constants to the Program class for the Event Hubs connection string and the event hub name. 请将括号中的占位符替换为在创建事件中心时获取的适当值。Replace placeholders in brackets with the proper values that you got when creating the event hub. 请将括号中的占位符替换为创建事件中心和存储帐户时获取的适当值(访问密钥 - 主连接字符串)。Replace placeholders in brackets with the proper values that you got when creating the event hub and the storage account (access keys - primary connection string). 请确保 {Event Hubs namespace connection string} 是命名空间级别的连接字符串,而不是事件中心字符串。Make sure that the {Event Hubs namespace connection string} is the namespace-level connection string, and not the event hub string.

        private const string ehubNamespaceConnectionString = "<EVENT HUBS NAMESPACE - CONNECTION STRING>";
        private const string eventHubName = "<EVENT HUB NAME>";
        private const string blobStorageConnectionString = "<AZURE STORAGE CONNECTION STRING>";
        private const string blobContainerName = "<BLOB CONTAINER NAME>";
    
  3. Main 方法替换为以下 async Main 方法。Replace the Main method with the following async Main method. 参阅代码注释了解详细信息。See the code comments for details.

        static async Task Main()
        {
            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;
    
            // Create a blob container client that the event processor will use 
            BlobContainerClient storageClient = new BlobContainerClient(blobStorageConnectionString, blobContainerName);
    
            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, ehubNamespaceConnectionString, eventHubName);
    
            // Register handlers for processing events and handling errors
            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;
    
            // Start the processing
            await processor.StartProcessingAsync();
    
            // Wait for 10 seconds for the events to be processed
            await Task.Delay(TimeSpan.FromSeconds(10));
    
            // Stop the processing
            await processor.StopProcessingAsync();
        }    
    
  4. 现在,将以下事件和错误处理程序方法添加到类中。Now, add the following event and error handler methods to the class.

        static async Task ProcessEventHandler(ProcessEventArgs eventArgs)
        {
            // Write the body of the event to the console window
            Console.WriteLine("\tRecevied event: {0}", Encoding.UTF8.GetString(eventArgs.Data.Body.ToArray()));
    
            // Update checkpoint in the blob storage so that the app receives only new events the next time it's run
            await eventArgs.UpdateCheckpointAsync(eventArgs.CancellationToken);
        }
    
        static Task ProcessErrorHandler(ProcessErrorEventArgs eventArgs)
        {
            // Write details about the error to the console window
            Console.WriteLine($"\tPartition '{ eventArgs.PartitionId}': an unhandled exception was encountered. This was not expected to happen.");
            Console.WriteLine(eventArgs.Exception.Message);
            return Task.CompletedTask;
        }    
    
  5. 生成项目并确保没有错误。Build the project, and ensure that there are no errors.

    Note

    有关包含更详细注释的完整源代码,请参阅 GitHub 上的此文件For the complete source code with more informational comments, see this file on the GitHub.

  6. 运行接收器应用程序。Run the receiver application.

  7. 应会看到一条消息,指出已接收事件。You should see a message that the event has been received.

    已接收事件

    这些事件是前面通过运行发送器程序发送到事件中心的三个事件。These events are the three events you sent to the event hub earlier by running the sender program.

后续步骤Next steps

查看 GitHub 上的示例。Check out the samples on GitHub.