Community寫作與編輯github.com

microsoft/azure-eventhub-dotnet

Azure Event Hubs 的 .NET SDK。用於高吞吐量事件串流:傳送事件(EventHubProducerClient、EventHubBufferedProducerClient)、接收事件(含檢查點的 EventProcessorClient)、分割區管理以及即時資料擷取。觸發詞:「Event Hubs」、「event streaming」、「EventHubProducerClient」、「EventProcessorClient」、「send events」、「receive events」、「checkpointing」、「partition」。

azure-eventhub-dotnet 是什麼?

此技能提供 Azure.Messaging.EventHubs .NET SDK 的完整指南,用於建置高效能的事件串流應用程式。它詳細說明如何透過非同步批次傳送或使用緩衝生產者,以及如何使用事件處理器用戶端搭配 Azure Blob 儲存體檢查點進行穩健的事件處理。支援傳送事件、處理分割區(包括分割區鍵和標識符)、以及實作生產檢查點策略等核心工作流程。此技能還涵蓋 ASP.NET Core 整合、錯誤處理最佳做法,以及使用 DefaultAzureCredential 透過 Azure 身分識別進行驗證。它明確指出哪些用戶端類型適用於生產環境(例如,對於接收端,始終使用 EventProcessorClient 而非 EventHubConsumerClient),並提供完整的程式碼範例,以實現即時事件串流或高輸送量的批次案例。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-eventhub-dotnet

Installed? Explore more 寫作與編輯 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Azure.Messaging.EventHubs (.NET)

用於透過 Azure Event Hubs 傳送和接收事件的高吞吐量事件串流 SDK。

安裝

# 核心套件(傳送和簡易接收)
dotnet add package Azure.Messaging.EventHubs

# 處理器套件(含檢查點的生產環境接收)
dotnet add package Azure.Messaging.EventHubs.Processor

# 驗證
dotnet add package Azure.Identity

# 檢查點(EventProcessorClient 需要)
dotnet add package Azure.Storage.Blobs

目前版本:Azure.Messaging.EventHubs v5.12.2、Azure.Messaging.EventHubs.Processor v5.12.2

環境變數

EVENTHUB_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net  # 必要項目:Event Hubs 完整限定命名空間
EVENTHUB_NAME=<event-hub-name>  # 必要項目:Event Hub 名稱
BLOB_STORAGE_CONNECTION_STRING=<storage-connection-string>  # 可取代 Entra ID 驗證
BLOB_CONTAINER_NAME=<checkpoint-container>  # 必要項目:檢查點容器名稱
EVENTHUB_CONNECTION_STRING=Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=...  # 可取代 Entra ID 驗證
AZURE_TOKEN_CREDENTIALS=prod  # 僅在生產環境使用 DefaultAzureCredential 時需要

驗證

using Azure.Identity;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;

// 本機開發:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或者直接在生產環境使用特定認證:
// 請參閱 https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();

var fullyQualifiedNamespace = Environment.GetEnvironmentVariable("EVENTHUB_FULLY_QUALIFIED_NAMESPACE");
var eventHubName = Environment.GetEnvironmentVariable("EVENTHUB_NAME");

var producer = new EventHubProducerClient(
    fullyQualifiedNamespace,
    eventHubName,
    credential);

必要的 RBAC 角色:

  • 傳送:Azure Event Hubs Data Sender
  • 接收:Azure Event Hubs Data Receiver
  • 兩者兼具:Azure Event Hubs Data Owner

用戶端類型

用戶端用途使用時機
EventHubProducerClient立即以批次方式傳送事件即時傳送,完全控制批次處理
EventHubBufferedProducerClient自動批次處理與背景傳送高容量、發送後即忘的案例
EventHubConsumerClient簡單的事件讀取僅限原型開發,不適用於生產環境
EventProcessorClient生產環境事件處理在生產環境中接收事件時務必使用此用戶端

核心工作流程

1. 傳送事件(批次)

using Azure.Identity;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;

await using var producer = new EventHubProducerClient(
    fullyQualifiedNamespace,
    eventHubName,
    new DefaultAzureCredential());

// 建立批次(自動遵守大小限制)
using EventDataBatch batch = await producer.CreateBatchAsync();

// 將事件新增至批次
var events = new[]
{
    new EventData(BinaryData.FromString("{\"id\": 1, \"message\": \"Hello\"}")),
    new EventData(BinaryData.FromString("{\"id\": 2, \"message\": \"World\"}"))
};

foreach (var eventData in events)
{
    if (!batch.TryAdd(eventData))
    {
        // 批次已滿 - 傳送它並建立新的批次
        await producer.SendAsync(batch);
        batch = await producer.CreateBatchAsync();
        
        if (!batch.TryAdd(eventData))
        {
            throw new Exception("對於空的批次來說,事件太大");
        }
    }
}

// 傳送剩餘的事件
if (batch.Count > 0)
{
    await producer.SendAsync(batch);
}

2. 傳送事件(緩衝 - 高容量)

using Azure.Messaging.EventHubs.Producer;

var options = new EventHubBufferedProducerClientOptions
{
    MaximumWaitTime = TimeSpan.FromSeconds(1)
};

await using var producer = new EventHubBufferedProducerClient(
    fullyQualifiedNamespace,
    eventHubName,
    new DefaultAzureCredential(),
    options);

// 處理傳送成功/失敗
producer.SendEventBatchSucceededAsync += args =>
{
    Console.WriteLine($"批次已傳送:{args.EventBatch.Count} 個事件");
    return Task.CompletedTask;
};

producer.SendEventBatchFailedAsync += args =>
{
    Console.WriteLine($"批次失敗:{args.Exception.Message}");
    return Task.CompletedTask;
};

// 將事件加入佇列(在背景中自動傳送)
for (int i = 0; i < 1000; i++)
{
    await producer.EnqueueEventAsync(new EventData($"Event {i}"));
}

// 在處置前清除剩餘的事件
await producer.FlushAsync();

3. 接收事件(生產環境 - EventProcessorClient)

using Azure.Identity;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Consumer;
using Azure.Messaging.EventHubs.Processor;
using Azure.Storage.Blobs;

// 用於檢查點的 Blob 容器
var blobClient = new BlobContainerClient(
    Environment.GetEnvironmentVariable("BLOB_STORAGE_CONNECTION_STRING"),
    Environment.GetEnvironmentVariable("BLOB_CONTAINER_NAME"));

await blobClient.CreateIfNotExistsAsync();

// 建立處理器
var processor = new EventProcessorClient(
    blobClient,
    EventHubConsumerClient.DefaultConsumerGroup,
    fullyQualifiedNamespace,
    eventHubName,
    new DefaultAzureCredential());

// 處理事件
processor.ProcessEventAsync += async args =>
{
    Console.WriteLine($"分割區:{args.Partition.PartitionId}");
    Console.WriteLine($"資料:{args.Data.EventBody}");
    
    // 處理後建立檢查點(或批次檢查點)
    await args.UpdateCheckpointAsync();
};

// 處理錯誤
processor.ProcessErrorAsync += args =>
{
    Console.WriteLine($"錯誤:{args.Exception.Message}");
    Console.WriteLine($"分割區:{args.PartitionId}");
    return Task.CompletedTask;
};

// 開始處理
await processor.StartProcessingAsync();

// 執行直到取消
await Task.Delay(Timeout.Infinite, cancellationToken);

// 正常停止
await processor.StopProcessingAsync();

4. 分割區操作

// 取得分割區標識符
string[] partitionIds = await producer.GetPartitionIdsAsync();

// 傳送至特定分割區(請謹慎使用)
var options = new SendEventOptions
{
    PartitionId = "0"
};
await producer.SendAsync(events, options);

// 使用分割區鍵(建議用於排序)
var batchOptions = new CreateBatchOptions
{
    PartitionKey = "customer-123"  // 具有相同鍵的事件會進入同一個分割區
};
using var batch = await producer.CreateBatchAsync(batchOptions);

EventPosition 選項

控制從何處開始讀取:

// 從開頭開始
EventPosition.Earliest

// 從結尾開始(僅限新事件)
EventPosition.Latest

// 從特定位移開始
EventPosition.FromOffset(12345)

// 從特定序號開始
EventPosition.FromSequenceNumber(100)

// 從特定時間開始
EventPosition.FromEnqueuedTime(DateTimeOffset.UtcNow.AddHours(-1))

ASP.NET Core 整合

// Program.cs
using Azure.Identity;
using Azure.Messaging.EventHubs.Producer;
using Microsoft.Extensions.Azure;

builder.Services.AddAzureClients(clientBuilder =>
{
    clientBuilder.AddEventHubProducerClient(
        builder.Configuration["EventHub:FullyQualifiedNamespace"],
        builder.Configuration["EventHub:Name"]);
    
    clientBuilder.UseCredential(new DefaultAzureCredential());
});

// 在控制器/服務中注入
public class EventService
{
    private readonly EventHubProducerClient _producer;
    
    public EventService(EventHubProducerClient producer)
    {
        _producer = producer;
    }
    
    public async Task SendAsync(string message)
    {
        using var batch = await _producer.CreateBatchAsync();
        batch.TryAdd(new EventData(message));
        await _producer.SendAsync(batch);
    }
}

最佳做法

  1. 使用 EventProcessorClient 進行接收 — 切勿在生產環境中使用 EventHubConsumerClient
  2. 策略性地建立檢查點 — 在 N 個事件或時間間隔後,而不是每個事件都建立
  3. 使用分割區鍵 — 以確保分割區內的排序保證
  4. 重複使用用戶端 — 建立一次,以單例方式使用(執行緒安全)
  5. 使用 await using — 確保適當的處置
  6. 處理 ProcessErrorAsync — 務必註冊錯誤處理常式
  7. 批次處理事件 — 使用 CreateBatchAsync() 來遵守大小限制
  8. 使用緩衝生產者 — 適用於具有自動批次處理的高容量案例

錯誤處理

using Azure.Messaging.EventHubs;

try
{
    await producer.SendAsync(batch);
}
catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ServiceBusy)
{
    // 使用指數退避重試
    await Task.Delay(TimeSpan.FromSeconds(5));
}
catch (EventHubsException ex) when (ex.IsTransient)
{
    // 暫時性錯誤 - 可以安全重試
    Console.WriteLine($"暫時性錯誤:{ex.Message}");
}
catch (EventHubsException ex)
{
    // 非暫時性錯誤
    Console.WriteLine($"錯誤:{ex.Reason} - {ex.Message}");
}

檢查點策略

策略使用時機
每個事件低容量、關鍵資料
每 N 個事件平衡吞吐量/可靠性
基於時間一致的檢查點間隔
批次完成處理邏輯批次後
// 每 100 個事件建立檢查點
private int _eventCount = 0;

processor.ProcessEventAsync += async args =>
{
    // 處理事件...
    
    _eventCount++;
    if (_eventCount >= 100)
    {
        await args.UpdateCheckpointAsync();
        _eventCount = 0;
    }
};

相關 SDK

SDK用途安裝
Azure.Messaging.EventHubs核心傳送/接收dotnet add package Azure.Messaging.EventHubs
Azure.Messaging.EventHubs.Processor生產環境處理dotnet add package Azure.Messaging.EventHubs.Processor
Azure.ResourceManager.EventHubs管理平面(建立中樞)dotnet add package Azure.ResourceManager.EventHubs
Microsoft.Azure.WebJobs.Extensions.EventHubsAzure Functions 繫結dotnet add package Microsoft.Azure.WebJobs.Extensions.EventHubs

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

相關技能