CommunityRedacción y edicióngithub.com

microsoft/azure-eventhub-dotnet

SDK de Azure Event Hubs para .NET. Úselo para la transmisión de eventos de alto rendimiento: envío de eventos (EventHubProducerClient, EventHubBufferedProducerClient), recepción de eventos (EventProcessorClient con checkpointing), administración de particiones y ingesta de datos en tiempo real. Activadores: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

¿Qué es azure-eventhub-dotnet?

El asistente Azure.Messaging.EventHubs para .NET proporciona un SDK de alto rendimiento para la transmisión de eventos mediante Azure Event Hubs. Está diseñado para desarrolladores que necesitan ingerir, procesar y analizar grandes volúmenes de datos de eventos en tiempo real. El asistente admite el envío de eventos con control total de lotes (EventHubProducerClient) o con agrupación automática en segundo plano para escenarios de alto volumen (EventHubBufferedProducerClient). Para la recepción en producción, se recomienda EventProcessorClient, que gestiona particiones y puntos de control (checkpointing) usando Azure Blob Storage para garantizar la fiabilidad y la reanudación del procesamiento. El asistente también incluye soporte para autenticación con Azure Identity, integración con ASP.NET Core y guías sobre estrategias de checkpointing y manejo de errores.

Compatible con~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 Redacción y edición skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Azure.Messaging.EventHubs (.NET)

SDK de transmisión de eventos de alto rendimiento para enviar y recibir eventos mediante Azure Event Hubs.

Instalación

# Paquete principal (envío y recepción simple)
dotnet add package Azure.Messaging.EventHubs

# Paquete de procesador (recepción en producción con checkpointing)
dotnet add package Azure.Messaging.EventHubs.Processor

# Autenticación
dotnet add package Azure.Identity

# Para checkpointing (requerido por EventProcessorClient)
dotnet add package Azure.Storage.Blobs

Versiones actuales: Azure.Messaging.EventHubs v5.12.2, Azure.Messaging.EventHubs.Processor v5.12.2

Variables de entorno

EVENTHUB_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net  # Requerido: Espacio de nombres completo de Event Hubs
EVENTHUB_NAME=<event-hub-name>  # Requerido: Nombre del Event Hub
BLOB_STORAGE_CONNECTION_STRING=<storage-connection-string>  # Alternativa a la autenticación de Entra ID
BLOB_CONTAINER_NAME=<checkpoint-container>  # Requerido: Nombre del contenedor de puntos de control
EVENTHUB_CONNECTION_STRING=Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=...  # Alternativa a la autenticación de Entra ID
AZURE_TOKEN_CREDENTIALS=prod  # Requerido solo si se usa DefaultAzureCredential en producción

Autenticación

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

// Desarrollo local: DefaultAzureCredential. Producción: establezca AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credential_especifica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// O use una credencial específica directamente en producción:
// Consulte 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);

Roles de RBAC requeridos:

  • Envío: Azure Event Hubs Data Sender
  • Recepción: Azure Event Hubs Data Receiver
  • Ambos: Azure Event Hubs Data Owner

Tipos de cliente

ClientePropósitoCuándo usarlo
EventHubProducerClientEnviar eventos inmediatamente en lotesEnvío en tiempo real, control total sobre los lotes
EventHubBufferedProducerClientAgrupación automática con envío en segundo planoEscenarios de alto volumen y de tipo "disparar y olvidar"
EventHubConsumerClientLectura simple de eventosSolo para prototipos, NO para producción
EventProcessorClientProcesamiento de eventos en producciónÚselo siempre para recepción en producción

Flujo de trabajo principal

1. Enviar eventos (lote)

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

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

// Crear un lote (respeta los límites de tamaño automáticamente)
using EventDataBatch batch = await producer.CreateBatchAsync();

// Agregar eventos al lote
var events = new[]
{
    new EventData(BinaryData.FromString("{\"id\": 1, \"message\": \"Hola\"}")),
    new EventData(BinaryData.FromString("{\"id\": 2, \"message\": \"Mundo\"}"))
};

foreach (var eventData in events)
{
    if (!batch.TryAdd(eventData))
    {
        // El lote está lleno - enviarlo y crear uno nuevo
        await producer.SendAsync(batch);
        batch = await producer.CreateBatchAsync();
        
        if (!batch.TryAdd(eventData))
        {
            throw new Exception("El evento es demasiado grande para un lote vacío");
        }
    }
}

// Enviar eventos restantes
if (batch.Count > 0)
{
    await producer.SendAsync(batch);
}

2. Enviar eventos (almacenado en búfer - Alto 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);

// Manejar éxito/fallo del envío
producer.SendEventBatchSucceededAsync += args =>
{
    Console.WriteLine($"Lote enviado: {args.EventBatch.Count} eventos");
    return Task.CompletedTask;
};

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

// Poner eventos en cola (se envían automáticamente en segundo plano)
for (int i = 0; i < 1000; i++)
{
    await producer.EnqueueEventAsync(new EventData($"Evento {i}"));
}

// Vaciar eventos restantes antes de desechar
await producer.FlushAsync();

3. Recibir eventos (Producción - EventProcessorClient)

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

// Contenedor de blobs para puntos de control
var blobClient = new BlobContainerClient(
    Environment.GetEnvironmentVariable("BLOB_STORAGE_CONNECTION_STRING"),
    Environment.GetEnvironmentVariable("BLOB_CONTAINER_NAME"));

await blobClient.CreateIfNotExistsAsync();

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

// Manejar eventos
processor.ProcessEventAsync += async args =>
{
    Console.WriteLine($"Partición: {args.Partition.PartitionId}");
    Console.WriteLine($"Datos: {args.Data.EventBody}");
    
    // Punto de control después del procesamiento (o puntos de control por lotes)
    await args.UpdateCheckpointAsync();
};

// Manejar errores
processor.ProcessErrorAsync += args =>
{
    Console.WriteLine($"Error: {args.Exception.Message}");
    Console.WriteLine($"Partición: {args.PartitionId}");
    return Task.CompletedTask;
};

// Iniciar procesamiento
await processor.StartProcessingAsync();

// Ejecutar hasta que se cancele
await Task.Delay(Timeout.Infinite, cancellationToken);

// Detener correctamente
await processor.StopProcessingAsync();

4. Operaciones de partición

// Obtener IDs de partición
string[] partitionIds = await producer.GetPartitionIdsAsync();

// Enviar a una partición específica (usar con moderación)
var options = new SendEventOptions
{
    PartitionId = "0"
};
await producer.SendAsync(events, options);

// Usar clave de partición (recomendado para orden)
var batchOptions = new CreateBatchOptions
{
    PartitionKey = "cliente-123"  // Los eventos con la misma clave van a la misma partición
};
using var batch = await producer.CreateBatchAsync(batchOptions);

Opciones de EventPosition

Controlar desde dónde empezar a leer:

// Empezar desde el principio
EventPosition.Earliest

// Empezar desde el final (solo eventos nuevos)
EventPosition.Latest

// Empezar desde un desplazamiento específico
EventPosition.FromOffset(12345)

// Empezar desde un número de secuencia específico
EventPosition.FromSequenceNumber(100)

// Empezar desde una hora específica
EventPosition.FromEnqueuedTime(DateTimeOffset.UtcNow.AddHours(-1))

Integración con 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());
});

// Inyectar en el controlador/servicio
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);
    }
}

Mejores prácticas

  1. Use EventProcessorClient para recepción — Nunca use EventHubConsumerClient en producción
  2. Puntos de control estratégicos — Después de N eventos o un intervalo de tiempo, no en cada evento
  3. Use claves de partición — Para garantías de orden dentro de una partición
  4. Reutilice clientes — Cree una vez, use como singleton (seguro para subprocesos)
  5. Use await using — Asegura una eliminación adecuada
  6. Maneje ProcessErrorAsync — Siempre registre un controlador de errores
  7. Agrupe eventos en lotes — Use CreateBatchAsync() para respetar los límites de tamaño
  8. Use el productor almacenado en búfer — Para escenarios de alto volumen con agrupación automática

Manejo de errores

using Azure.Messaging.EventHubs;

try
{
    await producer.SendAsync(batch);
}
catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ServiceBusy)
{
    // Reintentar con retroceso
    await Task.Delay(TimeSpan.FromSeconds(5));
}
catch (EventHubsException ex) when (ex.IsTransient)
{
    // Error transitorio - seguro de reintentar
    Console.WriteLine($"Error transitorio: {ex.Message}");
}
catch (EventHubsException ex)
{
    // Error no transitorio
    Console.WriteLine($"Error: {ex.Reason} - {ex.Message}");
}

Estrategias de checkpointing

EstrategiaCuándo usarla
Cada eventoBajo volumen, datos críticos
Cada N eventosRendimiento/fiabilidad equilibrados
Basada en tiempoIntervalos de punto de control consistentes
Finalización del loteDespués de procesar un lote lógico
// Punto de control cada 100 eventos
private int _eventCount = 0;

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

SDKs relacionados

SDKPropósitoInstalación
Azure.Messaging.EventHubsEnvío/recepción principaldotnet add package Azure.Messaging.EventHubs
Azure.Messaging.EventHubs.ProcessorProcesamiento en produccióndotnet add package Azure.Messaging.EventHubs.Processor
Azure.ResourceManager.EventHubsPlano de administración (crear hubs)dotnet add package Azure.ResourceManager.EventHubs
Microsoft.Azure.WebJobs.Extensions.EventHubsEnlace de 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 relacionados