Communityライティング&編集github.com

Azure Event Hubs .NET SDK

Azure Event Hubs の .NET SDK です。イベントストリーミング、送受信、パーティション管理、チェックポイント処理に対応します。

Azure Event Hubs .NET SDK とは?

このスキルは、Azure Event Hubs の .NET 用 SDK (`Azure.Messaging.EventHubs`) を活用するための包括的なガイドです。高スループットのイベントストリーミングを実現し、`EventHubProducerClient` を使用したバッチ送信、`EventHubBufferedProducerClient` を使用した自動バッファリングとバックグラウンド送信、そしてプロダクション環境での受信には `EventProcessorClient` を使用したチェックポイント処理をサポートします。このスキルは、開発者が環境変数や Azure Identity ライブラリを用いた認証方法、パーティション管理、エラーハンドリング、チェックポイント戦略、ASP.NET Core との統合方法を理解するのに役立ちます。CLI コマンド `dotnet add package` で簡単にインストールでき、コード例も豊富に含まれているため、実際のアプリケーションにすぐに組み込むことができます。

対応~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=<特定の資格情報>
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.

関連スキル