CommunitySchreiben & Editierengithub.com

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK für .NET. Verwenden Sie es für hochdurchsatzfähiges Event-Streaming: Senden von Ereignissen (EventHubProducerClient, EventHubBufferedProducerClient), Empfangen von Ereignissen (EventProcessorClient mit Checkpointing), Partitionsverwaltung und Echtzeit-Datenerfassung.

Was ist azure-eventhub-dotnet?

Diese Fähigkeit beschreibt das Azure.Messaging.EventHubs .NET SDK, das für hochdurchsatzfähiges Event-Streaming in Azure Event Hubs konzipiert ist. Es ermöglicht Entwicklern das Senden von Ereignissen in Batches mit `EventHubProducerClient` oder automatisch gepuffert mit `EventHubBufferedProducerClient` für Szenarien mit hohem Volumen. Für den produktiven Empfang wird `EventProcessorClient` empfohlen, der Checkpointing in Azure Blob Storage unterstützt, um eine zuverlässige Verarbeitung und Wiederaufnahme nach Fehlern zu gewährleisten. Die Fähigkeit behandelt die Installation, Authentifizierung über Azure Identity (DefaultAzureCredential), Partitionierung, EventPosition-Konfiguration, ASP.NET Core-Integration und Best Practices wie Checkpointing-Strategien und Fehlerbehandlung – alles spezifisch für .NET-Entwickler, die Azure Event Hubs nutzen.

Funktioniert mit~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 Schreiben & Editieren skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Azure.Messaging.EventHubs (.NET)

Hochdurchsatzfähiges Event-Streaming-SDK zum Senden und Empfangen von Ereignissen über Azure Event Hubs.

Installation

# Kernpaket (Senden und einfaches Empfangen)
dotnet add package Azure.Messaging.EventHubs

# Prozessor-Paket (produktives Empfangen mit Checkpointing)
dotnet add package Azure.Messaging.EventHubs.Processor

# Authentifizierung
dotnet add package Azure.Identity

# Für Checkpointing (erforderlich für EventProcessorClient)
dotnet add package Azure.Storage.Blobs

Aktuelle Versionen: Azure.Messaging.EventHubs v5.12.2, Azure.Messaging.EventHubs.Processor v5.12.2

Umgebungsvariablen

EVENTHUB_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net  # Erforderlich: Vollqualifizierter Event Hubs-Namespace
EVENTHUB_NAME=<event-hub-name>  # Erforderlich: Event Hub-Name
BLOB_STORAGE_CONNECTION_STRING=<storage-connection-string>  # Alternative zur Entra ID-Authentifizierung
BLOB_CONTAINER_NAME=<checkpoint-container>  # Erforderlich: Name des Checkpoint-Containers
EVENTHUB_CONNECTION_STRING=Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=...  # Alternative zur Entra ID-Authentifizierung
AZURE_TOKEN_CREDENTIALS=prod  # Nur erforderlich, wenn DefaultAzureCredential in der Produktion verwendet wird

Authentifizierung

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

// Lokale Entwicklung: DefaultAzureCredential. Produktion: setze AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Oder verwende direkt ein spezifisches Anmeldeinformation in der Produktion:
// Siehe 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);

Erforderliche RBAC-Rollen:

  • Senden: Azure Event Hubs Data Sender
  • Empfangen: Azure Event Hubs Data Receiver
  • Beides: Azure Event Hubs Data Owner

Client-Typen

ClientZweckWann verwenden
EventHubProducerClientEreignisse sofort in Batches sendenEchtzeit-Senden, volle Kontrolle über Batchverarbeitung
EventHubBufferedProducerClientAutomatische Batchverarbeitung mit HintergrundversandSzenarien mit hohem Volumen und "Feuer und Vergiss"
EventHubConsumerClientEinfaches Lesen von EreignissenNur für Prototypen, NICHT für die Produktion
EventProcessorClientProduktive EreignisverarbeitungImmer für das Empfangen in der Produktion verwenden

Kern-Workflow

1. Ereignisse senden (Batch)

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

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

// Einen Batch erstellen (respektiert Größenbeschränkungen automatisch)
using EventDataBatch batch = await producer.CreateBatchAsync();

// Ereignisse zum Batch hinzufügen
var events = new[]
{
    new EventData(BinaryData.FromString("{\"id\": 1, \"message\": \"Hallo\"}")),
    new EventData(BinaryData.FromString("{\"id\": 2, \"message\": \"Welt\"}"))
};

foreach (var eventData in events)
{
    if (!batch.TryAdd(eventData))
    {
        // Batch ist voll - senden und einen neuen erstellen
        await producer.SendAsync(batch);
        batch = await producer.CreateBatchAsync();
        
        if (!batch.TryAdd(eventData))
        {
            throw new Exception("Ereignis zu groß für leeren Batch");
        }
    }
}

// Verbleibende Ereignisse senden
if (batch.Count > 0)
{
    await producer.SendAsync(batch);
}

2. Ereignisse senden (Gepuffert - Hohes Volumen)

using Azure.Messaging.EventHubs.Producer;

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

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

// Erfolg/Fehler beim Senden behandeln
producer.SendEventBatchSucceededAsync += args =>
{
    Console.WriteLine($"Batch gesendet: {args.EventBatch.Count} Ereignisse");
    return Task.CompletedTask;
};

producer.SendEventBatchFailedAsync += args =>
{
    Console.WriteLine($"Batch fehlgeschlagen: {args.Exception.Message}");
    return Task.CompletedTask;
};

// Ereignisse in die Warteschlange stellen (werden automatisch im Hintergrund gesendet)
for (int i = 0; i < 1000; i++)
{
    await producer.EnqueueEventAsync(new EventData($"Ereignis {i}"));
}

// Verbleibende Ereignisse vor dem Freigeben leeren
await producer.FlushAsync();

3. Ereignisse empfangen (Produktion - EventProcessorClient)

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

// Blob-Container für Checkpointing
var blobClient = new BlobContainerClient(
    Environment.GetEnvironmentVariable("BLOB_STORAGE_CONNECTION_STRING"),
    Environment.GetEnvironmentVariable("BLOB_CONTAINER_NAME"));

await blobClient.CreateIfNotExistsAsync();

// Prozessor erstellen
var processor = new EventProcessorClient(
    blobClient,
    EventHubConsumerClient.DefaultConsumerGroup,
    fullyQualifiedNamespace,
    eventHubName,
    new DefaultAzureCredential());

// Ereignisse behandeln
processor.ProcessEventAsync += async args =>
{
    Console.WriteLine($"Partition: {args.Partition.PartitionId}");
    Console.WriteLine($"Daten: {args.Data.EventBody}");
    
    // Checkpoint nach der Verarbeitung (oder Batch-Checkpoints)
    await args.UpdateCheckpointAsync();
};

// Fehler behandeln
processor.ProcessErrorAsync += args =>
{
    Console.WriteLine($"Fehler: {args.Exception.Message}");
    Console.WriteLine($"Partition: {args.PartitionId}");
    return Task.CompletedTask;
};

// Verarbeitung starten
await processor.StartProcessingAsync();

// Bis zur Stornierung ausführen
await Task.Delay(Timeout.Infinite, cancellationToken);

// Ordentlich beenden
await processor.StopProcessingAsync();

4. Partitionsoperationen

// Partitions-IDs abrufen
string[] partitionIds = await producer.GetPartitionIdsAsync();

// An eine bestimmte Partition senden (sparsam verwenden)
var options = new SendEventOptions
{
    PartitionId = "0"
};
await producer.SendAsync(events, options);

// Partitionsschlüssel verwenden (empfohlen für Reihenfolge)
var batchOptions = new CreateBatchOptions
{
    PartitionKey = "customer-123"  // Ereignisse mit gleichem Schlüssel kommen in dieselbe Partition
};
using var batch = await producer.CreateBatchAsync(batchOptions);

EventPosition-Optionen

Kontrolliere, wo mit dem Lesen begonnen wird:

// Am Anfang beginnen
EventPosition.Earliest

// Am Ende beginnen (nur neue Ereignisse)
EventPosition.Latest

// Bei einem bestimmten Offset beginnen
EventPosition.FromOffset(12345)

// Bei einer bestimmten Sequenznummer beginnen
EventPosition.FromSequenceNumber(100)

// Zu einem bestimmten Zeitpunkt beginnen
EventPosition.FromEnqueuedTime(DateTimeOffset.UtcNow.AddHours(-1))

ASP.NET Core-Integration

// 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());
});

// In Controller/Service injizieren
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);
    }
}

Best Practices

  1. EventProcessorClient für den Empfang verwenden — EventHubConsumerClient niemals in der Produktion nutzen
  2. Strategisch checkpointen — Nach N Ereignissen oder einem Zeitintervall, nicht nach jedem Ereignis
  3. Partitionsschlüssel verwenden — Für Reihenfolgegarantien innerhalb einer Partition
  4. Clients wiederverwenden — Einmal erstellen, als Singleton verwenden (threadsicher)
  5. await using verwenden — Stellt ordnungsgemäße Freigabe sicher
  6. ProcessErrorAsync behandeln — Immer einen Fehlerhandler registrieren
  7. Ereignisse bündeln — CreateBatchAsync() verwenden, um Größenbeschränkungen einzuhalten
  8. Gepufferten Producer verwenden — Für Szenarien mit hohem Volumen und automatischer Batchverarbeitung

Fehlerbehandlung

using Azure.Messaging.EventHubs;

try
{
    await producer.SendAsync(batch);
}
catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ServiceBusy)
{
    // Wiederholen mit Backoff
    await Task.Delay(TimeSpan.FromSeconds(5));
}
catch (EventHubsException ex) when (ex.IsTransient)
{
    // Transienter Fehler - sicher zu wiederholen
    Console.WriteLine($"Transienter Fehler: {ex.Message}");
}
catch (EventHubsException ex)
{
    // Nicht-transienter Fehler
    Console.WriteLine($"Fehler: {ex.Reason} - {ex.Message}");
}

Checkpointing-Strategien

StrategieWann verwenden
Jedes EreignisGeringes Volumen, kritische Daten
Alle N EreignisseAusgewogener Durchsatz/Zuverlässigkeit
ZeitbasiertKonsistente Checkpoint-Intervalle
Batch-AbschlussNach der Verarbeitung eines logischen Batches
// Checkpoint alle 100 Ereignisse
private int _eventCount = 0;

processor.ProcessEventAsync += async args =>
{
    // Ereignis verarbeiten...
    
    _eventCount++;
    if (_eventCount >= 100)
    {
        await args.UpdateCheckpointAsync();
        _eventCount = 0;
    }
};

Verwandte SDKs

SDKZweckInstallation
Azure.Messaging.EventHubsKernfunktionen Senden/Empfangendotnet add package Azure.Messaging.EventHubs
Azure.Messaging.EventHubs.ProcessorProduktive Verarbeitungdotnet add package Azure.Messaging.EventHubs.Processor
Azure.ResourceManager.EventHubsVerwaltungsebene (Hubs erstellen)dotnet add package Azure.ResourceManager.EventHubs
Microsoft.Azure.WebJobs.Extensions.EventHubsAzure Functions-Bindungdotnet 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.

Verwandte Skills