共用方式為


.NET Aspire Azure Event Hubs 整合

Azure Event Hubs 是雲端中的原生數據串流服務,每秒可串流數百萬個事件,且延遲低,從任何來源到任何目的地。 .NET Aspire Azure Event Hubs 整合可讓您從 .NET 應用程式連線到 Azure Event Hubs 實例。

託管整合

主機整合 .NET.NET AspireAzure Event Hubs 會將各種事件中樞資源模型化為下列類型:

若要存取這些類型和 API,以在 應用程式主機 專案中表示它們,請安裝 📦Aspire.Hosting.Azure.EventHubs NuGet 套件:

dotnet add package Aspire.Hosting.Azure.EventHubs

如需詳細資訊,請參閱 dotnet add package管理 .NET 應用程式中的套件相依性

新增 Azure Event Hubs 資源

若要將 AzureEventHubsResource 新增至您的應用程式主專案,請呼叫提供名稱的 AddAzureEventHubs 方法,然後呼叫 AddHub

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs");
eventHubs.AddHub("messages");

builder.AddProject<Projects.ExampleService>()
       .WithReference(eventHubs);

// After adding all resources, run the app...

當您將 Azure Event Hubs 資源新增至應用程式主機時,它會公開其他有用的 API,以新增事件中樞資源、消費者群組、指定明確的布建設定,並啟用 Azure Event Hubs 模擬器。 上述程式代碼會將名為 event-hubs 的 Azure Event Hubs 資源,以及名為 messages 的事件中樞新增至應用程式主機專案。 WithReference 方法會將連接資訊傳遞至 ExampleService 專案。

重要

當您呼叫 AddAzureEventHubs時,它會隱含地呼叫 AddAzureProvisioning(IDistributedApplicationBuilder),這可新增在應用程式啟動期間動態產生 Azure 資源的支援。 應用程式必須設定適當的訂用帳戶和位置。 若要取得更多資訊,請參閱本機設定 :組態

自動化生成的佈署 Bicep

如果您不熟悉 Bicep,這是一種用於定義 Azure 資源的領域專用語言。 使用 .NET.NET Aspire,您不需要手動撰寫 Bicep,佈建 API 會為您自動產生 Bicep。 當您發佈應用程式時,生成的 Bicep 會與清單檔案一起輸出。 當您新增 Azure Event Hubs 資源時,會產生下列 Bicep:

@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location

param sku string = 'Standard'

param principalType string

param principalId string

resource event_hubs 'Microsoft.EventHub/namespaces@2024-01-01' = {
  name: take('event_hubs-${uniqueString(resourceGroup().id)}', 256)
  location: location
  sku: {
    name: sku
  }
  tags: {
    'aspire-resource-name': 'event-hubs'
  }
}

resource event_hubs_AzureEventHubsDataOwner 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(event_hubs.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'f526a384-b230-433a-b45c-95f59c4a2dec'))
  properties: {
    principalId: principalId
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'f526a384-b230-433a-b45c-95f59c4a2dec')
    principalType: principalType
  }
  scope: event_hubs
}

resource messages 'Microsoft.EventHub/namespaces/eventhubs@2024-01-01' = {
  name: 'messages'
  parent: event_hubs
}

output eventHubsEndpoint string = event_hubs.properties.serviceBusEndpoint

上述 Bicep 模組會布建一個資源 Azure Event Hubs,其具有以下預設值:

  • location:資源群組的位置。
  • sku:事件中樞資源的 SKU 預設為 Standard
  • principalId:事件中樞資源的主體標識符。
  • principalType:事件中樞資源的主體類型。
  • event_hubs:事件中樞命名空間資源。
  • event_hubs_AzureEventHubsDataOwner:事件中樞資源擁有者,以內建 Azure Event Hubs Data Owner 角色為基礎。 如需詳細資訊,請參閱 Azure Event Hubs 資料擁有者
  • messages:事件中樞資源。
  • eventHubsEndpoint:事件中樞資源的端點。

產生的 Bicep 是起始點,可以進一步自定義以符合您的特定需求。

自訂佈署基礎結構

所有 .NET AspireAzure 資源都是 AzureProvisioningResource 類型的子類別。 此類型可藉由提供 Fluent API 來設定 Azure 資源,藉此自定義產生的 Bicep,方法是使用 ConfigureInfrastructure<T>(IResourceBuilder<T>, Action<AzureResourceInfrastructure>) API。 例如,您可以設定 kindconsistencyPolicylocations等等。 下列範例示範如何自訂 AzureAzure Cosmos DB 資源:

builder.AddAzureEventHubs("event-hubs")
    .ConfigureInfrastructure(infra =>
    {
        var eventHubs = infra.GetProvisionableResources()
                             .OfType<EventHubsNamespace>()
                             .Single();

        eventHubs.Sku = new EventHubsSku()
        {
            Name = EventHubsSkuName.Premium,
            Tier = EventHubsSkuTier.Premium,
            Capacity = 7,
        };
        eventHubs.PublicNetworkAccess = EventHubsPublicNetworkAccess.SecuredByPerimeter;
        eventHubs.Tags.Add("ExampleKey", "Example value");
    });

上述程式代碼:

還有許多更多組態選項可用來自訂事件中樞資源。 如需詳細資訊,請參閱 Azure.Provisioning.PostgreSql。 如需詳細資訊,請參閱 Azure.Provisioning 自訂

連接到現有的 Azure Event Hubs 命名空間

您可能有想要連線的現有 Azure Event Hubs 命名空間。 您可以將連接字串新增至應用程式主機,而不是代表新的 Azure Event Hubs 資源。 若要將連線新增至現有的 Azure Event Hubs 命名空間,請呼叫 AddConnectionString 方法:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddConnectionString("event-hubs");

builder.AddProject<Projects.WebApplication>("web")
       .WithReference(eventHubs);

// After adding all resources, run the app...

備註

連接字串可用來代表各種連線資訊,包括資料庫連接、訊息代理程式、端點 URI 和其他服務。 在 .NET.NET Aspire 名詞中,「連接字串」一詞用來代表任何類型的連接資訊。

連接字串是在應用程式主機的組態中設定,通常是在 [] 區段下的 [ConnectionStrings下。 應用程式主機會將此連接字串作為環境變數插入所有相依資源,例如:

{
  "ConnectionStrings": {
    "event-hubs": "{your_namespace}.servicebus.windows.net"
  }
}

相依資源可以藉由呼叫 GetConnectionString 方法來存取插入的連接字串,並將連接名稱傳遞為 參數,在此情況下 "event-hubs"GetConnectionString API 是 IConfiguration.GetSection("ConnectionStrings")[name]的簡寫。

新增事件中樞取用者群組

若要新增取用者群組,請將 IResourceBuilder<AzureEventHubsResource> 的呼叫鏈結至 AddConsumerGroup API:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs");
var messages = eventHubs.AddHub("messages");
messages.AddConsumerGroup("messagesConsumer");

builder.AddProject<Projects.ExampleService>()
       .WithReference(eventHubs);

// After adding all resources, run the app...

當您呼叫 AddConsumerGroup時,它會將 messages 事件中樞資源設定為具有名為 messagesConsumer的取用者群組。 取用者群組會在您稍早新增 AzureEventHubsResource 所代表的 Azure Event Hubs 命名空間中建立。 如需詳細資訊,請參閱 Azure Event Hubs:取用者群組

新增 Azure Event Hubs 模擬器資源

.NET Aspire Azure Event Hubs 主控整合支持根據 mcr.microsoft.com/azure-messaging/eventhubs-emulator/latest 容器映像檔,在本機以模擬器方式執行事件中樞資源。 這適用於您想要在本機執行事件中樞資源以供開發和測試之用的情況,避免需要布建 Azure 資源或連線到現有的 Azure Event Hubs 伺服器。

若要以模擬器身分執行事件中樞資源,請呼叫 RunAsEmulator 方法:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs")
                       .RunAsEmulator();

eventHubs.AddHub("messages");

var exampleProject = builder.AddProject<Projects.ExampleProject>()
                            .WithReference(eventHubs);

// After adding all resources, run the app...

上述程式代碼會設定 Azure Event Hubs 資源,以在容器中本地執行。 如需詳細資訊,請參閱 Azure Event Hubs 模擬器

設定事件中樞模擬器容器

容器資源有多種配置選項可用,例如,您可以設定容器的連接埠、資料綁定掛載、資料卷,或提供一個能覆蓋所有設定的整體 JSON 配置。

設定事件中樞模擬器容器主機埠

根據預設,.NET.NET Aspire設定的事件中樞模擬器容器會公開下列端點:

端點 圖片 集裝箱港口 主機埠
emulator mcr.microsoft.com/azure-messaging/eventhubs-emulator/latest 5672 動態

接聽的埠預設為動態。 當容器啟動時,埠會對應至主計算機上的隨機埠。 若要設定端點埠,請依序在 RunAsEmulator 方法提供的容器資源生成器上進行鏈結呼叫,然後接著 WithHostPort(IResourceBuilder<AzureEventHubsEmulatorResource>, Nullable<Int32>),如下列範例所示:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs")
                       .RunAsEmulator(emulator =>
                       {
                           emulator.WithHostPort(7777);
                       });

eventHubs.AddHub("messages");

builder.AddProject<Projects.ExampleService>()
       .WithReference(eventHubs);

// After adding all resources, run the app...

此程式代碼會設定 Azure 事件模擬器容器的現有 emulator 連接點,以接聽埠 7777。 Azure 事件模擬器容器的埠會對應至主機埠,如下表所示:

端點名稱 連接埠對應 (container:host
emulator 5672:7777
新增具備數據流量的事件中樞模擬器

若要將數據磁碟區新增至事件中樞模擬器資源,請在事件中樞模擬器資源上呼叫 WithDataVolume 方法:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs")
                       .RunAsEmulator(emulator =>
                       {
                           emulator.WithDataVolume();
                       });

eventHubs.AddHub("messages");

builder.AddProject<Projects.ExampleService>()
       .WithReference(eventHubs);

// After adding all resources, run the app...

數據磁碟區可用來將事件中樞模擬器數據保存在其容器生命週期之外。 數據卷會掛載在容器中的 /data 路徑。 除非您提供設定 name 參數,否則會隨機產生名稱。 如需有關資料量的詳細資訊,以及為何它們比 系結掛接更受偏好的原因,請參閱 Docker 檔:磁碟區

新增具有資料掛載的事件中樞模擬器

將系結掛接新增至事件中樞模擬器容器,並將呼叫鏈結至 WithDataBindMount API,如下列範例所示:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs")
                       .RunAsEmulator(emulator =>
                       {
                           emulator.WithDataBindMount("/path/to/data");
                       });

eventHubs.AddHub("messages");

builder.AddProject<Projects.ExampleService>()
       .WithReference(eventHubs);

// After adding all resources, run the app...

重要

相較於 系結掛載 的功能有限,磁碟區提供更佳的效能、可移植性和安全性,使其更適合生產環境。 不過,綁定掛載允許直接存取和修改主機系統上的檔案,非常適合用於開發和測試中需要即時變更的情況。

數據系結掛接依賴主計算機的文件系統,在容器重新啟動時保存 Azure Event Hubs 模擬器資源數據。 數據系結掛接會掛接在容器中主計算機上的 /path/to/data 路徑上。 如需資料系結掛接的詳細資訊,請參閱 Docker 檔:系結掛接

設定事件中樞模擬器容器 JSON 設定

事件中樞模擬器容器會以預設 config.json 檔案執行。 您可以完全覆寫此檔案,或使用組態的 JSON 表示法來更新 JsonNode 組態。

若要提供自訂 JSON 組態檔,請呼叫 WithConfigurationFile(IResourceBuilder<AzureEventHubsEmulatorResource>, String) 方法:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs")
                       .RunAsEmulator(emulator =>
                       {
                           emulator.WithConfigurationFile("./messaging/custom-config.json");
                       });

eventHubs.AddHub("messages");

builder.AddProject<Projects.ExampleService>()
       .WithReference(eventHubs);

// After adding all resources, run the app...

上述程式代碼會設定事件中樞模擬器容器,以使用位於 ./messaging/custom-config.json的自定義 JSON 組態檔。 這會掛載在容器的 /Eventhubs_Emulator/ConfigFiles/Config.json 路徑上,以只讀方式提供。 若要改為覆寫預設組態中的特定屬性,請呼叫 WithConfiguration(IResourceBuilder<AzureEventHubsEmulatorResource>, Action<JsonNode>) 方法:

var builder = DistributedApplication.CreateBuilder(args);

var eventHubs = builder.AddAzureEventHubs("event-hubs")
                       .RunAsEmulator(emulator =>
                       {
                           emulator.WithConfiguration(
                               (JsonNode configuration) =>
                               {
                                   var userConfig = configuration["UserConfig"];
                                   var ns = userConfig["NamespaceConfig"][0];
                                   var firstEntity = ns["Entities"][0];
                                   
                                   firstEntity["PartitionCount"] = 5;
                               });
                       });

eventHubs.AddHub("messages");

builder.AddProject<Projects.ExampleService>()
       .WithReference(eventHubs);

// After adding all resources, run the app...

上述程式代碼會從預設組態擷取 UserConfig 節點。 然後,它會將第一個實體的 PartitionCount 更新為 5

託管集成健全性檢查

整合主機 Azure Event Hubs 會自動為事件中樞資源新增健康檢查。 健康情況檢查會確認事件中樞正在執行,而且可以建立與其連線。

裝載整合依賴 📦 AspNetCore.HealthChecksAzureMessaging.EventHubs NuGet 套件。

Client 整合

若要開始使用 .NET AspireAzure Event Hubs 用戶端整合,請在用戶端取用專案中安裝 NuGet 套件 📦Aspire。Azure。Messaging.EventHubs,也就是使用事件中樞用戶端的應用程式專案。

dotnet add package Aspire.Azure.Messaging.EventHubs

支援的事件中樞客戶端類型

程式庫支援以下事件中心用戶端,以及其對應的選項和設定類別:

Azure 客戶端類型 Azure 選項類別 .NET .NET Aspire 設定類別
EventHubProducerClient EventHubProducerClientOptions AzureMessagingEventHubsProducerSettings
EventHubBufferedProducerClient EventHubBufferedProducerClientOptions AzureMessagingEventHubsBufferedProducerSettings
EventHubConsumerClient EventHubConsumerClientOptions AzureMessagingEventHubsConsumerSettings
EventProcessorClient EventProcessorClientOptions AzureMessagingEventHubsProcessorSettings
PartitionReceiver PartitionReceiverOptions AzureMessagingEventHubsPartitionReceiverSettings

用戶端類型來自適用於 .NET的 Azure SDK,對應的選項類別也一樣。 設定類別是由 .NET.NET Aspire提供。 設定類別可用來設定客戶端實例。

新增事件中樞產生者用戶端

在用戶端專案的 Program.cs 檔案中,對任意的 AddAzureEventHubProducerClient 呼叫 IHostApplicationBuilder 擴充方法,以透過相依性注入容器註冊 EventHubProducerClient 並使用。 方法會採用連接名稱參數。

builder.AddAzureEventHubProducerClient(connectionName: "event-hubs");

小提示

connectionName 參數必須符合在應用程式主機專案中新增事件中樞資源時所使用的名稱。 如需詳細資訊,請參閱 新增 Azure Event Hubs 資源

新增 EventHubProducerClient之後,您可以使用相依性插入來擷取客戶端實例。 例如,若要從範例服務擷取數據源物件,請將其定義為建構函式參數,並確定已向相依性插入容器註冊 ExampleService 類別:

public class ExampleService(EventHubProducerClient client)
{
    // Use client...
}

如需詳細資訊,請參閱:

要考慮的其他 API

用戶端整合提供其他 API 來設定客戶端實例。 當您需要註冊事件中樞用戶端時,請考慮下列 API:

Azure 客戶端類型 註冊應用程式介面
EventHubProducerClient AddAzureEventHubProducerClient
EventHubBufferedProducerClient AddAzureEventHubBufferedProducerClient
EventHubConsumerClient AddAzureEventHubConsumerClient
EventProcessorClient AddAzureEventProcessorClient
PartitionReceiver AddAzurePartitionReceiverClient

上述所有 API 都包含選擇性參數來設定客戶端實例。

新增索引鍵事件中樞產生者用戶端

在某些情況下,您可能想要以不同的連線名稱註冊多個 EventHubProducerClient 實例。 若要註冊具有索引鍵的事件中樞客戶端,請呼叫 AddKeyedAzureServiceBusClient 方法。

builder.AddKeyedAzureEventHubProducerClient(name: "messages");
builder.AddKeyedAzureEventHubProducerClient(name: "commands");

重要

在使用鍵控服務時,預期您的事件中樞資源已設定兩個命名中樞,一個用於 messages,另一個用於 commands

然後,您可以使用相依性插入來擷取客戶端實例。 例如,若要從服務中擷取客戶:

public class ExampleService(
    [KeyedService("messages")] EventHubProducerClient messagesClient,
    [KeyedService("commands")] EventHubProducerClient commandsClient)
{
    // Use clients...
}

如需詳細資訊,請參閱 .NET內的鍵控服務。

需要考慮的其他重要 API

用戶端整合提供其他 API 來設定金鑰式用戶端實例。 當您需要註冊金鑰事件中樞用戶端時,請考慮下列 API:

Azure 客戶端類型 註冊 API
EventHubProducerClient AddKeyedAzureEventHubProducerClient
EventHubBufferedProducerClient AddKeyedAzureEventHubBufferedProducerClient
EventHubConsumerClient AddKeyedAzureEventHubConsumerClient
EventProcessorClient AddKeyedAzureEventProcessorClient
PartitionReceiver AddKeyedAzurePartitionReceiverClient

上述所有 API 都包含選擇性參數來設定客戶端實例。

配置

.NET Aspire Azure Event Hubs 連結庫提供多個選項,根據專案的需求和慣例來設定 Azure Event Hubs 連線。 必須提供 FullyQualifiedNamespaceConnectionString 任一項。

使用連接字串

從 [ConnectionStrings 組態] 區段使用連接字串時,請在呼叫 builder.AddAzureEventHubProducerClient() 和其他支援的事件中樞用戶端時,提供連接字串的名稱。 在這裡範例中,連接字串不包含 EntityPath 屬性,因此必須在設定回呼中設定 EventHubName 屬性:

builder.AddAzureEventHubProducerClient(
    "event-hubs",
    static settings =>
    {
        settings.EventHubName = "MyHub";
    });

然後,將會從 [ConnectionStrings 組態] 區段擷取連線資訊。 支援兩種連線格式:

完整命名空間 (FQN)

建議的方法是使用完整命名空間,其可與 AzureMessagingEventHubsSettings.Credential 屬性搭配使用,以建立連線。 如果未設定認證,則會使用 DefaultAzureCredential

{
  "ConnectionStrings": {
    "event-hubs": "{your_namespace}.servicebus.windows.net"
  }
}

連接字串

或者,使用連接字串:

{
  "ConnectionStrings": {
    "event-hubs": "Endpoint=sb://mynamespace.servicebus.windows.net/;SharedAccessKeyName=accesskeyname;SharedAccessKey=accesskey;EntityPath=MyHub"
  }
}

使用組態提供者

.NET Aspire Azure Event Hubs 連結庫支援 Microsoft.Extensions.Configuration。 它會使用 AzureMessagingEventHubsSettings 索引鍵前置詞,從配置中載入 EventProcessorClientOptions 和相關選項,例如 Aspire:Azure:Messaging:EventHubs:,然後接著特定客戶端的名稱。 例如,請考慮 appsettings.json,它設定了一些 EventProcessorClient的選項:

{
  "Aspire": {
    "Azure": {
      "Messaging": {
        "EventHubs": {
          "EventProcessorClient": {
            "EventHubName": "MyHub",
            "ClientOptions": {
              "Identifier": "PROCESSOR_ID"
            }
          }
        }
      }
    }
  }
}

您也可以使用 Action<IAzureClientBuilder<EventProcessorClient, EventProcessorClientOptions>> configureClientBuilder 方法的選擇性 AddAzureEventProcessorClient 參數來設定選項類型。 例如,若要設定此用戶端的處理器用戶端識別碼:

builder.AddAzureEventProcessorClient(
    "event-hubs",
    configureClientBuilder: clientBuilder => clientBuilder.ConfigureOptions(
        options => options.Identifier = "PROCESSOR_ID"));

可檢視性和遙測

.NET .NET Aspire 整合會自動設定記錄、追蹤和指標組態,有時稱為 可觀察性的支柱。 如需整合可觀察性和遙測的詳細資訊,請參閱 .NET.NET Aspire 整合概觀。 視支援服務而定,某些整合可能只支援其中一些功能。 例如,某些整合支援記錄和追蹤,但不支援計量。 您也可以使用 組態 一節中呈現的技術來停用遙測功能。

伐木

.NET Aspire Azure Event Hubs 整合會使用下列記錄類別:

  • Azure.Core
  • Azure.Identity

追蹤

.NET Aspire Azure Event Hubs 整合會使用 OpenTelemetry發出下列追蹤活動:

  • Azure.Messaging.EventHubs.*

指標

.NET Aspire Azure Event Hubs 整合目前預設不支援度量,因為 Azure SDK 對於 .NET的限制。 如果未來發生該變更,本節將會更新以反映這些變更。

另請參閱