Community写作与编辑github.com

microsoft/azure-eventhub-dotnet

用于 .NET 的 Azure 事件中心 SDK。支持高吞吐量事件流:发送事件(EventHubProducerClient、EventHubBufferedProducerClient)、接收事件(带检查点的 EventProcessorClient)、分区管理以及实时数据摄取。

azure-eventhub-dotnet 是什么?

该技能详细介绍了适用于 .NET 的 Azure.Messaging.EventHubs SDK,它将 Azure 事件中心的高吞吐量事件流功能无缝集成到与 AI 智能体兼容的环境中。它提供了两个主要客户端的详细配置:用于实时批量发送的 EventHubProducerClient 和用于高容量“发送即忘”场景(后台自动批量处理)的 EventHubBufferedProducerClient。在接收方面,它强调将 EventProcessorClient 用于生产工作负载,该客户端通过 Azure Blob 存储提供可靠的检查点功能,以在分区内实现精确的一次处理语义。该文档包含完整的代码示例,涵盖设置环境变量、使用 DefaultAzureCredential(支持 ManagedIdentityCredential)进行身份验证、使用分区键或直接分区 ID 进行分区操作,以及通过各种 EventPosition 选项控制开始读取位置。此外,它还涵盖 ASP.NET Core 集成、最佳实践(例如跨服务复用客户端、战略性检查点以减少存储 I/O,以及使用 await using 进行正确清除)以及区分可重试和不可重试故障的稳健错误处理策略。总体而言,它是任何在受支持平台上使用 .NET 构建事件驱动架构的开发人员的必备资源。

兼容平台~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 事件中心发送和接收事件的高吞吐量事件流 SDK。

安装

# 核心包(发送和简单接收)
dotnet add package Azure.Messaging.EventHubs

# Processor 包(带检查点的生产环境接收)
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  # 必需:事件中心完全限定命名空间
EVENTHUB_NAME=<event-hub-name>  # 必需:事件中心名称
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. 分区操作

// 获取分区 ID
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.

相关技能