CommunityEscrita e Ediçãogithub.com

microsoft/azure-eventhub-dotnet

SDK do Azure Event Hubs para .NET. Use para streaming de eventos de alta taxa de transferência: envio de eventos (EventHubProducerClient, EventHubBufferedProducerClient), recebimento de eventos (EventProcessorClient com checkpointing), gerenciamento de partições e ingestão de dados em tempo real.

O que é azure-eventhub-dotnet?

Este skill fornece o SDK completo do Azure Event Hubs para .NET, permitindo que agentes de IA integrem streaming de eventos de alta taxa de transferência em aplicações .NET. Ele suporta dois modos principais de envio: o `EventHubProducerClient` para controle total sobre lotes e o `EventHubBufferedProducerClient` para cenários de alto volume com envio automático em segundo plano. Para recebimento, o `EventProcessorClient` é a escolha recomendada para produção, oferecendo checkpointing baseado em Azure Blob Storage para processamento confiável e tolerante a falhas. O skill cobre autenticação via `DefaultAzureCredential` e entidades gerenciadas, operações de partição, estratégias de checkpointing, integração com ASP.NET Core e práticas recomendadas para tratamento de erros. Os desenvolvedores podem usar este skill para construir pipelines de dados em tempo real, processar eventos em lote e garantir ordenação e escalabilidade com partições e chaves de partição. É compatível com os pacotes NuGet `Azure.Messaging.EventHubs` e `Azure.Messaging.EventHubs.Processor`, e pode ser utilizado em qualquer ferramenta de agente que suporte .NET, como Cursor, Codex ou Claude Code, fornecendo exemplos de código prontos para uso e configurações de ambiente.

Funciona com~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 Escrita e Edição skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Azure.Messaging.EventHubs (.NET)

SDK de streaming de eventos de alta taxa de transferência para enviar e receber eventos por meio do Azure Event Hubs.

Instalação

# Pacote principal (envio e recebimento simples)
dotnet add package Azure.Messaging.EventHubs

# Pacote do processador (recebimento em produção com checkpointing)
dotnet add package Azure.Messaging.EventHubs.Processor

# Autenticação
dotnet add package Azure.Identity

# Para checkpointing (necessário para EventProcessorClient)
dotnet add package Azure.Storage.Blobs

Versões Atuais: Azure.Messaging.EventHubs v5.12.2, Azure.Messaging.EventHubs.Processor v5.12.2

Variáveis de Ambiente

EVENTHUB_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net  # Obrigatório: namespace totalmente qualificado do Event Hubs
EVENTHUB_NAME=<nome-do-eventhub>  # Obrigatório: nome do Event Hub
BLOB_STORAGE_CONNECTION_STRING=<string-de-conexao-do-storage>  # Alternativa à autenticação via Entra ID
BLOB_CONTAINER_NAME=<container-de-checkpoint>  # Obrigatório: nome do container de checkpoint
EVENTHUB_CONNECTION_STRING=Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=...  # Alternativa à autenticação via Entra ID
AZURE_TOKEN_CREDENTIALS=prod  # Obrigatório apenas se DefaultAzureCredential for usado em produção

Autenticação

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

// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credencial_especifica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou use uma credencial específica diretamente em produção:
// 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);

Funções RBAC Necessárias:

  • Envio: Azure Event Hubs Data Sender
  • Recebimento: Azure Event Hubs Data Receiver
  • Ambos: Azure Event Hubs Data Owner

Tipos de Cliente

ClienteFinalidadeQuando Usar
EventHubProducerClientEnviar eventos imediatamente em lotesEnvio em tempo real, controle total sobre lotes
EventHubBufferedProducerClientLotes automáticos com envio em segundo planoCenários de alto volume, do tipo "disparar e esquecer"
EventHubConsumerClientLeitura simples de eventosSomente prototipagem, NÃO para produção
EventProcessorClientProcessamento de eventos em produçãoSempre use este para recebimento em produção

Fluxo de Trabalho 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());

// Crie um lote (respeita limites de tamanho automaticamente)
using EventDataBatch batch = await producer.CreateBatchAsync();

// Adicione eventos ao lote
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))
    {
        // Lote está cheio - envie-o e crie um novo
        await producer.SendAsync(batch);
        batch = await producer.CreateBatchAsync();
        
        if (!batch.TryAdd(eventData))
        {
            throw new Exception("Evento muito grande para um lote vazio");
        }
    }
}

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

2. Enviar Eventos (Bufferizado - Alto Volume)

using Azure.Messaging.EventHubs.Producer;

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

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

// Lidar com sucesso/falha do envio
producer.SendEventBatchSucceededAsync += args =>
{
    Console.WriteLine($"Lote enviado: {args.EventBatch.Count} eventos");
    return Task.CompletedTask;
};

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

// Enfileire eventos (enviados automaticamente em segundo plano)
for (int i = 0; i < 1000; i++)
{
    await producer.EnqueueEventAsync(new EventData($"Evento {i}"));
}

// Descarregue eventos restantes antes de descartar
await producer.FlushAsync();

3. Receber Eventos (Produção - EventProcessorClient)

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

// Container de blobs para checkpointing
var blobClient = new BlobContainerClient(
    Environment.GetEnvironmentVariable("BLOB_STORAGE_CONNECTION_STRING"),
    Environment.GetEnvironmentVariable("BLOB_CONTAINER_NAME"));

await blobClient.CreateIfNotExistsAsync();

// Crie o processador
var processor = new EventProcessorClient(
    blobClient,
    EventHubConsumerClient.DefaultConsumerGroup,
    fullyQualifiedNamespace,
    eventHubName,
    new DefaultAzureCredential());

// Lidar com eventos
processor.ProcessEventAsync += async args =>
{
    Console.WriteLine($"Partição: {args.Partition.PartitionId}");
    Console.WriteLine($"Dados: {args.Data.EventBody}");
    
    // Checkpoint após processamento (ou checkpoints em lote)
    await args.UpdateCheckpointAsync();
};

// Lidar com erros
processor.ProcessErrorAsync += args =>
{
    Console.WriteLine($"Erro: {args.Exception.Message}");
    Console.WriteLine($"Partição: {args.PartitionId}");
    return Task.CompletedTask;
};

// Iniciar processamento
await processor.StartProcessingAsync();

// Executar até ser cancelado
await Task.Delay(Timeout.Infinite, cancellationToken);

// Parar graciosamente
await processor.StopProcessingAsync();

4. Operações de Partição

// Obter IDs de partição
string[] partitionIds = await producer.GetPartitionIdsAsync();

// Enviar para partição específica (use com moderação)
var options = new SendEventOptions
{
    PartitionId = "0"
};
await producer.SendAsync(events, options);

// Usar chave de partição (recomendado para ordenação)
var batchOptions = new CreateBatchOptions
{
    PartitionKey = "cliente-123"  // Eventos com a mesma chave vão para a mesma partição
};
using var batch = await producer.CreateBatchAsync(batchOptions);

Opções de EventPosition

Controle de onde começar a ler:

// Começar do início
EventPosition.Earliest

// Começar do final (novos eventos apenas)
EventPosition.Latest

// Começar de um offset específico
EventPosition.FromOffset(12345)

// Começar de um número de sequência específico
EventPosition.FromSequenceNumber(100)

// Começar de um horário específico
EventPosition.FromEnqueuedTime(DateTimeOffset.UtcNow.AddHours(-1))

Integração com 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());
});

// Injetar em controller/serviço
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);
    }
}

Práticas Recomendadas

  1. Use EventProcessorClient para recebimento — Nunca use EventHubConsumerClient em produção
  2. Faça checkpoint estrategicamente — Após N eventos ou intervalo de tempo, não a cada evento
  3. Use chaves de partição — Para garantias de ordenação dentro de uma partição
  4. Reutilize clientes — Crie uma vez, use como singleton (thread-safe)
  5. Use await using — Garante descarte adequado
  6. Lide com ProcessErrorAsync — Sempre registre um manipulador de erros
  7. Agrupe eventos — Use CreateBatchAsync() para respeitar limites de tamanho
  8. Use o produtor bufferizado — Para cenários de alto volume com lotes automáticos

Tratamento de Erros

using Azure.Messaging.EventHubs;

try
{
    await producer.SendAsync(batch);
}
catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ServiceBusy)
{
    // Tentar novamente com backoff
    await Task.Delay(TimeSpan.FromSeconds(5));
}
catch (EventHubsException ex) when (ex.IsTransient)
{
    // Erro transitório - seguro tentar novamente
    Console.WriteLine($"Erro transitório: {ex.Message}");
}
catch (EventHubsException ex)
{
    // Erro não transitório
    Console.WriteLine($"Erro: {ex.Reason} - {ex.Message}");
}

Estratégias de Checkpointing

EstratégiaQuando Usar
A cada eventoVolume baixo, dados críticos
A cada N eventosThroughput/confiabilidade equilibrados
Baseada em tempoIntervalos de checkpoint consistentes
Após conclusão do loteApós processar um lote lógico
// Checkpoint a cada 100 eventos
private int _eventCount = 0;

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

SDKs Relacionados

SDKFinalidadeInstalar
Azure.Messaging.EventHubsEnvio/recebimento principaldotnet add package Azure.Messaging.EventHubs
Azure.Messaging.EventHubs.ProcessorProcessamento em produçãodotnet add package Azure.Messaging.EventHubs.Processor
Azure.ResourceManager.EventHubsPlano de gerenciamento (criar hubs)dotnet add package Azure.ResourceManager.EventHubs
Microsoft.Azure.WebJobs.Extensions.EventHubsBinding do 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.

Habilidades Relacionadas