CommunityRédaction et éditiongithub.com

microsoft/azure-eventhub-dotnet

SDK Azure Event Hubs pour .NET. Utilisé pour le streaming d'événements à haut débit : envoi d'événements (EventHubProducerClient, EventHubBufferedProducerClient), réception d'événements (EventProcessorClient avec checkpointing), gestion des partitions et ingestion de données en temps réel.

Qu'est-ce que azure-eventhub-dotnet ?

Cette compétence fournit l'intégralité du SDK Azure.Messaging.EventHubs pour .NET, permettant aux agents IA de manipuler Azure Event Hubs pour le streaming d'événements à haut débit. Elle couvre l'envoi d'événements en lots (EventHubProducerClient) ou en mode tamponné avec envoi automatique en arrière-plan (EventHubBufferedProducerClient), ainsi que la réception fiable en production via EventProcessorClient avec checkpointing basé sur Azure Storage Blobs. La compétence détaille l'authentification via DefaultAzureCredential (ou ManagedIdentityCredential), les variables d'environnement requises, l'utilisation des clés de partition pour garantir l'ordre, les stratégies de checkpointing (par événement, tous les N événements, par intervalle de temps), l'intégration ASP.NET Core via Microsoft.Extensions.Azure, et la gestion des erreurs avec distinction entre erreurs transitoires et non transitoires. Elle prend en charge .NET et est conçue pour être utilisée avec des agents comme Claude Code, Cursor ou Codex pour automatiser des pipelines de données en temps réel.

Compatible avec~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 Rédaction et édition skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Azure.Messaging.EventHubs (.NET)

SDK de streaming d'événements à haut débit pour envoyer et recevoir des événements via Azure Event Hubs.

Installation

# Package principal (envoi et réception simple)
dotnet add package Azure.Messaging.EventHubs

# Package processeur (réception en production avec checkpointing)
dotnet add package Azure.Messaging.EventHubs.Processor

# Authentification
dotnet add package Azure.Identity

# Pour le checkpointing (requis par EventProcessorClient)
dotnet add package Azure.Storage.Blobs

Versions actuelles : Azure.Messaging.EventHubs v5.12.2, Azure.Messaging.EventHubs.Processor v5.12.2

Variables d'environnement

EVENTHUB_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net  # Requis : espace de noms qualifié complet Event Hubs
EVENTHUB_NAME=<event-hub-name>  # Requis : nom de l'Event Hub
BLOB_STORAGE_CONNECTION_STRING=<storage-connection-string>  # Alternative à l'authentification Entra ID
BLOB_CONTAINER_NAME=<checkpoint-container>  # Requis : nom du conteneur de checkpoint
EVENTHUB_CONNECTION_STRING=Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=...  # Alternative à l'authentification Entra ID
AZURE_TOKEN_CREDENTIALS=prod  # Requis uniquement si DefaultAzureCredential est utilisé en production

Authentification

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

// Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_spécifique>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou utiliser directement une information d'identification spécifique en production :
// Voir 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);

Rôles RBAC requis :

  • Envoi : Azure Event Hubs Data Sender
  • Réception : Azure Event Hubs Data Receiver
  • Les deux : Azure Event Hubs Data Owner

Types de clients

ClientObjectifQuand l'utiliser
EventHubProducerClientEnvoyer des événements immédiatement par lotsEnvoi en temps réel, contrôle total du regroupement
EventHubBufferedProducerClientRegroupement automatique avec envoi en arrière-planScénarios à volume élevé, "fire-and-forget"
EventHubConsumerClientLecture d'événements simplePrototypage uniquement, PAS pour la production
EventProcessorClientTraitement d'événements en productionToujours utiliser celui-ci pour la réception en production

Flux de travail principal

1. Envoyer des événements (par lots)

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

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

// Créer un lot (respecte automatiquement les limites de taille)
using EventDataBatch batch = await producer.CreateBatchAsync();

// Ajouter des événements au lot
var events = new[]
{
    new EventData(BinaryData.FromString("{\"id\": 1, \"message\": \"Bonjour\"}")),
    new EventData(BinaryData.FromString("{\"id\": 2, \"message\": \"Monde\"}"))
};

foreach (var eventData in events)
{
    if (!batch.TryAdd(eventData))
    {
        // Le lot est plein - l'envoyer et en créer un nouveau
        await producer.SendAsync(batch);
        batch = await producer.CreateBatchAsync();
        
        if (!batch.TryAdd(eventData))
        {
            throw new Exception("Événement trop grand pour un lot vide");
        }
    }
}

// Envoyer les événements restants
if (batch.Count > 0)
{
    await producer.SendAsync(batch);
}

2. Envoyer des événements (tamponné - volume élevé)

using Azure.Messaging.EventHubs.Producer;

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

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

// Gérer le succès/échec de l'envoi
producer.SendEventBatchSucceededAsync += args =>
{
    Console.WriteLine($"Lot envoyé : {args.EventBatch.Count} événements");
    return Task.CompletedTask;
};

producer.SendEventBatchFailedAsync += args =>
{
    Console.WriteLine($"Échec du lot : {args.Exception.Message}");
    return Task.CompletedTask;
};

// Mettre les événements en file d'attente (envoyés automatiquement en arrière-plan)
for (int i = 0; i < 1000; i++)
{
    await producer.EnqueueEventAsync(new EventData($"Événement {i}"));
}

// Vider les événements restants avant la suppression
await producer.FlushAsync();

3. Recevoir des événements (Production - EventProcessorClient)

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

// Conteneur Blob pour le checkpointing
var blobClient = new BlobContainerClient(
    Environment.GetEnvironmentVariable("BLOB_STORAGE_CONNECTION_STRING"),
    Environment.GetEnvironmentVariable("BLOB_CONTAINER_NAME"));

await blobClient.CreateIfNotExistsAsync();

// Créer le processeur
var processor = new EventProcessorClient(
    blobClient,
    EventHubConsumerClient.DefaultConsumerGroup,
    fullyQualifiedNamespace,
    eventHubName,
    new DefaultAzureCredential());

// Gérer les événements
processor.ProcessEventAsync += async args =>
{
    Console.WriteLine($"Partition : {args.Partition.PartitionId}");
    Console.WriteLine($"Données : {args.Data.EventBody}");
    
    // Effectuer le checkpoint après le traitement (ou par lots de checkpoints)
    await args.UpdateCheckpointAsync();
};

// Gérer les erreurs
processor.ProcessErrorAsync += args =>
{
    Console.WriteLine($"Erreur : {args.Exception.Message}");
    Console.WriteLine($"Partition : {args.PartitionId}");
    return Task.CompletedTask;
};

// Démarrer le traitement
await processor.StartProcessingAsync();

// Exécuter jusqu'à annulation
await Task.Delay(Timeout.Infinite, cancellationToken);

// Arrêter proprement
await processor.StopProcessingAsync();

4. Opérations sur les partitions

// Obtenir les ID de partition
string[] partitionIds = await producer.GetPartitionIdsAsync();

// Envoyer vers une partition spécifique (à utiliser avec parcimonie)
var options = new SendEventOptions
{
    PartitionId = "0"
};
await producer.SendAsync(events, options);

// Utiliser une clé de partition (recommandé pour l'ordre)
var batchOptions = new CreateBatchOptions
{
    PartitionKey = "client-123"  // Les événements avec la même clé vont dans la même partition
};
using var batch = await producer.CreateBatchAsync(batchOptions);

Options EventPosition

Contrôler où commencer la lecture :

// Commencer depuis le début
EventPosition.Earliest

// Commencer depuis la fin (nouveaux événements uniquement)
EventPosition.Latest

// Commencer depuis un décalage spécifique
EventPosition.FromOffset(12345)

// Commencer depuis un numéro de séquence spécifique
EventPosition.FromSequenceNumber(100)

// Commencer depuis une heure spécifique
EventPosition.FromEnqueuedTime(DateTimeOffset.UtcNow.AddHours(-1))

Intégration 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());
});

// Injection dans le contrôleur/service
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);
    }
}

Bonnes pratiques

  1. Utiliser EventProcessorClient pour la réception — Ne jamais utiliser EventHubConsumerClient en production
  2. Effectuer le checkpoint stratégiquement — Après N événements ou un intervalle de temps, pas après chaque événement
  3. Utiliser les clés de partition — Pour des garanties d'ordre au sein d'une partition
  4. Réutiliser les clients — Créer une fois, utiliser comme singleton (thread-safe)
  5. Utiliser await using — Garantit une suppression correcte
  6. Gérer ProcessErrorAsync — Toujours enregistrer un gestionnaire d'erreur
  7. Regrouper les événements — Utiliser CreateBatchAsync() pour respecter les limites de taille
  8. Utiliser le producteur tamponné — Pour les scénarios à volume élevé avec regroupement automatique

Gestion des erreurs

using Azure.Messaging.EventHubs;

try
{
    await producer.SendAsync(batch);
}
catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ServiceBusy)
{
    // Réessayer avec un délai d'attente
    await Task.Delay(TimeSpan.FromSeconds(5));
}
catch (EventHubsException ex) when (ex.IsTransient)
{
    // Erreur transitoire - sans risque de réessayer
    Console.WriteLine($"Erreur transitoire : {ex.Message}");
}
catch (EventHubsException ex)
{
    // Erreur non transitoire
    Console.WriteLine($"Erreur : {ex.Reason} - {ex.Message}");
}

Stratégies de checkpointing

StratégieQuand l'utiliser
Chaque événementFaible volume, données critiques
Tous les N événementsTrait équilibré débit/fiabilité
Basée sur le tempsIntervalles de checkpoint cohérents
À la fin d'un lotAprès le traitement d'un lot logique
// Checkpoint tous les 100 événements
private int _eventCount = 0;

processor.ProcessEventAsync += async args =>
{
    // Traiter l'événement...
    
    _eventCount++;
    if (_eventCount >= 100)
    {
        await args.UpdateCheckpointAsync();
        _eventCount = 0;
    }
};

Kits SDK associés

SDKObjectifInstallation
Azure.Messaging.EventHubsEnvoi/réception principaldotnet add package Azure.Messaging.EventHubs
Azure.Messaging.EventHubs.ProcessorTraitement en productiondotnet add package Azure.Messaging.EventHubs.Processor
Azure.ResourceManager.EventHubsPlan de gestion (créer des hubs)dotnet add package Azure.ResourceManager.EventHubs
Microsoft.Azure.WebJobs.Extensions.EventHubsLiaison Azure Functionsdotnet 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.

Skills associés