Community라이팅 & 에디팅github.com

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. 대용량 이벤트 스트리밍: 이벤트 전송(EventHubProducerClient, EventHubBufferedProducerClient), 이벤트 수신(EventProcessorClient, 체크포인트 포함), 파티션 관리, 실시간 데이터 수집.

azure-eventhub-dotnet란 무엇인가요?

Azure.Messaging.EventHubs(.NET)은 Azure Event Hubs를 통해 대규모 이벤트 스트리밍을 위한 공식 .NET SDK입니다. 이 SDK는 EventHubProducerClient와 EventHubBufferedProducerClient를 사용한 실시간 및 고성능 이벤트 전송, EventProcessorClient를 사용한 프로덕션 등급 이벤트 수신(체크포인트 지원), 파티션 관리 등 다양한 시나리오를 지원합니다. Azure.Identity를 통한 DefaultAzureCredential 인증을 기본으로 하며, 개발 환경과 프로덕션 환경에서 모두 사용 가능합니다. SDK는 .NET 개발자 도구(CLI, IDE) 및 ASP.NET Core 통합을 지원하며, Azure Functions, Event Grid 등 다른 Azure 서비스와 원활하게 연동됩니다. 핵심 워크플로는 배치 전송, 버퍼링된 전송, 프로덕션 수신(체크포인트 포함), 파티션 작업으로 구성되어 있으며, EventProcessorClient는 항상 프로덕션 환경에서 사용해야 합니다.

지원 대상~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에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Azure.Messaging.EventHubs (.NET)

Azure Event Hubs를 통해 이벤트를 전송 및 수신하기 위한 고처리량 이벤트 스트리밍 SDK입니다.

설치

# 핵심 패키지(전송 및 간단한 수신)
dotnet add package Azure.Messaging.EventHubs

# 프로세서 패키지(체크포인트 포함 프로덕션 수신)
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  # 필수: Event Hubs 정규화된 네임스페이스
EVENTHUB_NAME=<event-hub-name>  # 필수: Event Hub 이름
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백그라운드 전송으로 자동 배치대용량, fire-and-forget 시나리오
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.

관련 스킬