Azure.Messaging.EventGrid (.NET)
用於將事件發佈至 Azure Event Grid 主題、網域及命名空間的用戶端程式庫。
安裝
dotnet add package Azure.Messaging.EventGrid
dotnet add package Azure.Messaging.EventGrid.Namespaces
dotnet add package Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents
目前版本:4.28.0 (穩定版)
環境變數
EVENT_GRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events
EVENT_GRID_TOPIC_KEY=<access-key>
EVENT_GRID_NAMESPACE_ENDPOINT=https://<namespace>.<region>.eventgrid.azure.net
EVENT_GRID_TOPIC_NAME=<topic-name>
EVENT_GRID_SUBSCRIPTION_NAME=<subscription-name>
AZURE_TOKEN_CREDENTIALS=prod
用戶端階層
推送傳遞 (主題/網域)
└── EventGridPublisherClient
├── SendEventAsync(EventGridEvent)
├── SendEventsAsync(IEnumerable<EventGridEvent>)
├── SendEventAsync(CloudEvent)
└── SendEventsAsync(IEnumerable<CloudEvent>)
拉取傳遞 (命名空間)
├── EventGridSenderClient
│ └── SendAsync(CloudEvent)
└── EventGridReceiverClient
├── ReceiveAsync()
├── AcknowledgeAsync()
├── ReleaseAsync()
└── RejectAsync()
驗證
API 金鑰驗證
using Azure;
using Azure.Messaging.EventGrid;
EventGridPublisherClient client = new(
new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
new AzureKeyCredential("<access-key>"));
Microsoft Entra 權杖憑證
using Azure.Identity;
using Azure.Messaging.EventGrid;
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
EventGridPublisherClient client = new(
new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
credential);
SAS 權杖驗證
string sasToken = EventGridPublisherClient.BuildSharedAccessSignature(
new Uri(topicEndpoint),
DateTimeOffset.UtcNow.AddHours(1),
new AzureKeyCredential(topicKey));
var sasCredential = new AzureSasCredential(sasToken);
EventGridPublisherClient client = new(
new Uri(topicEndpoint),
sasCredential);
發佈事件
EventGridEvent 架構
EventGridPublisherClient client = new(
new Uri(topicEndpoint),
new AzureKeyCredential(topicKey));
EventGridEvent egEvent = new(
subject: "orders/12345",
eventType: "Order.Created",
dataVersion: "1.0",
data: new { OrderId = "12345", Amount = 99.99 });
await client.SendEventAsync(egEvent);
List<EventGridEvent> events = new()
{
new EventGridEvent(
subject: "orders/12345",
eventType: "Order.Created",
dataVersion: "1.0",
data: new OrderData { OrderId = "12345", Amount = 99.99 }),
new EventGridEvent(
subject: "orders/12346",
eventType: "Order.Created",
dataVersion: "1.0",
data: new OrderData { OrderId = "12346", Amount = 149.99 })
};
await client.SendEventsAsync(events);
CloudEvent 架構
CloudEvent cloudEvent = new(
source: "/orders/system",
type: "Order.Created",
data: new { OrderId = "12345", Amount = 99.99 });
cloudEvent.Subject = "orders/12345";
cloudEvent.Id = Guid.NewGuid().ToString();
cloudEvent.Time = DateTimeOffset.UtcNow;
await client.SendEventAsync(cloudEvent);
List<CloudEvent> cloudEvents = new()
{
new CloudEvent("/orders", "Order.Created", new { OrderId = "1" }),
new CloudEvent("/orders", "Order.Updated", new { OrderId = "2" })
};
await client.SendEventsAsync(cloudEvents);
發佈至 Event Grid 網域
List<EventGridEvent> events = new()
{
new EventGridEvent(
subject: "orders/12345",
eventType: "Order.Created",
dataVersion: "1.0",
data: new { OrderId = "12345" })
{
Topic = "orders-topic"
},
new EventGridEvent(
subject: "inventory/item-1",
eventType: "Inventory.Updated",
dataVersion: "1.0",
data: new { ItemId = "item-1" })
{
Topic = "inventory-topic"
}
};
await client.SendEventsAsync(events);
自訂序列化
using System.Text.Json;
var serializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var customSerializer = new JsonObjectSerializer(serializerOptions);
EventGridEvent egEvent = new(
subject: "orders/12345",
eventType: "Order.Created",
dataVersion: "1.0",
data: customSerializer.Serialize(new OrderData { OrderId = "12345" }));
await client.SendEventAsync(egEvent);
拉取傳遞 (命名空間)
傳送事件至命名空間主題
using Azure;
using Azure.Messaging;
using Azure.Messaging.EventGrid.Namespaces;
var senderClient = new EventGridSenderClient(
new Uri(namespaceEndpoint),
topicName,
new AzureKeyCredential(topicKey));
CloudEvent cloudEvent = new("employee_source", "Employee.Created",
new { Name = "John", Age = 30 });
await senderClient.SendAsync(cloudEvent);
await senderClient.SendAsync(new[]
{
new CloudEvent("source", "type", new { Name = "Alice" }),
new CloudEvent("source", "type", new { Name = "Bob" })
});
接收與處理事件
var receiverClient = new EventGridReceiverClient(
new Uri(namespaceEndpoint),
topicName,
subscriptionName,
new AzureKeyCredential(topicKey));
ReceiveResult result = await receiverClient.ReceiveAsync(maxEvents: 10);
List<string> lockTokensToAck = new();
List<string> lockTokensToRelease = new();
foreach (ReceiveDetails detail in result.Details)
{
CloudEvent cloudEvent = detail.Event;
string lockToken = detail.BrokerProperties.LockToken;
try
{
Console.WriteLine($"事件:{cloudEvent.Type},資料:{cloudEvent.Data}");
lockTokensToAck.Add(lockToken);
}
catch (Exception)
{
lockTokensToRelease.Add(lockToken);
}
}
if (lockTokensToAck.Any())
{
await receiverClient.AcknowledgeAsync(lockTokensToAck);
}
if (lockTokensToRelease.Any())
{
await receiverClient.ReleaseAsync(lockTokensToRelease);
}
拒絕事件 (死信)
await receiverClient.RejectAsync(new[] { lockToken });
消費事件 (Azure Functions)
EventGridEvent 觸發程序
using Azure.Messaging.EventGrid;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
public static class EventGridFunction
{
[FunctionName("ProcessEventGridEvent")]
public static void Run(
[EventGridTrigger] EventGridEvent eventGridEvent,
ILogger log)
{
log.LogInformation($"事件類型:{eventGridEvent.EventType}");
log.LogInformation($"主旨:{eventGridEvent.Subject}");
log.LogInformation($"資料:{eventGridEvent.Data}");
}
}
CloudEvent 觸發程序
using Azure.Messaging;
using Microsoft.Azure.Functions.Worker;
public class CloudEventFunction
{
[Function("ProcessCloudEvent")]
public void Run(
[EventGridTrigger] CloudEvent cloudEvent,
FunctionContext context)
{
var logger = context.GetLogger("ProcessCloudEvent");
logger.LogInformation($"事件類型:{cloudEvent.Type}");
logger.LogInformation($"來源:{cloudEvent.Source}");
logger.LogInformation($"資料:{cloudEvent.Data}");
}
}
剖析事件
剖析 EventGridEvent
string json = "...";
EventGridEvent[] events = EventGridEvent.ParseMany(BinaryData.FromString(json));
foreach (EventGridEvent egEvent in events)
{
if (egEvent.TryGetSystemEventData(out object systemEvent))
{
switch (systemEvent)
{
case StorageBlobCreatedEventData blobCreated:
Console.WriteLine($"Blob 已建立:{blobCreated.Url}");
break;
}
}
else
{
var customData = egEvent.Data.ToObjectFromJson<MyCustomData>();
}
}
剖析 CloudEvent
CloudEvent[] cloudEvents = CloudEvent.ParseMany(BinaryData.FromString(json));
foreach (CloudEvent cloudEvent in cloudEvents)
{
var data = cloudEvent.Data.ToObjectFromJson<MyEventData>();
Console.WriteLine($"類型:{cloudEvent.Type},資料:{data}");
}
系統事件
using Azure.Messaging.EventGrid.SystemEvents;
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;
WebAppUpdatedEventData webAppUpdated;
ContainerRegistryImagePushedEventData imagePushed;
IotHubDeviceCreatedEventData deviceCreated;
主要類型參考
| 類型 | 用途 |
|---|
EventGridPublisherClient | 發佈至主題/網域 |
EventGridSenderClient | 傳送至命名空間主題 |
EventGridReceiverClient | 從命名空間訂閱接收 |
EventGridEvent | Event Grid 原生結構描述 |
CloudEvent | CloudEvents 1.0 結構描述 |
ReceiveResult | 拉取傳遞回應 |
ReceiveDetails | 帶有代理程式屬性的事件 |
BrokerProperties | 鎖定權杖、傳遞計數 |
事件結構描述比較
| 功能 | EventGridEvent | CloudEvent |
|---|
| 標準 | Azure 專屬 | CNCF 標準 |
| 必要欄位 | subject、eventType、dataVersion、data | source、type |
| 擴充性 | 有限 | 擴充屬性 |
| 互通性 | 僅 Azure | 跨平台 |
最佳做法
- 使用 CloudEvents — 新實作建議採用 CloudEvents (業界標準)
- 批次事件 — 一次呼叫中傳送多個事件以提高效率
- 使用 Entra ID — 優先使用受控識別而非存取金鑰
- 等冪處理程式 — 事件可能重複傳送
- 設定事件 TTL — 為命名空間事件設定存活時間
- 處理部分失敗 — 個別確認/釋放事件
- 使用死信 — 為失敗事件設定死信
- 驗證結構描述 — 處理前先驗證事件資料
錯誤處理
using Azure;
try
{
await client.SendEventAsync(cloudEvent);
}
catch (RequestFailedException ex) when (ex.Status == 401)
{
Console.WriteLine("驗證失敗 - 檢查憑證");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
Console.WriteLine("授權失敗 - 檢查 RBAC 權限");
}
catch (RequestFailedException ex) when (ex.Status == 413)
{
Console.WriteLine("承載過大 - 每事件最大 1MB,批次總計最大 1MB");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Event Grid 錯誤:{ex.Status} - {ex.Message}");
}
容錯移轉模式
try
{
var primaryClient = new EventGridPublisherClient(primaryUri, primaryKey);
await primaryClient.SendEventsAsync(events);
}
catch (RequestFailedException)
{
var secondaryClient = new EventGridPublisherClient(secondaryUri, secondaryKey);
await secondaryClient.SendEventsAsync(events);
}
相關 SDK
| SDK | 用途 | 安裝指令 |
|---|
Azure.Messaging.EventGrid | 主題/網域 (此 SDK) | dotnet add package Azure.Messaging.EventGrid |
Azure.Messaging.EventGrid.Namespaces | 拉取傳遞 | dotnet add package Azure.Messaging.EventGrid.Namespaces |
Azure.Identity | 驗證 | dotnet add package Azure.Identity |
Microsoft.Azure.WebJobs.Extensions.EventGrid | Azure Functions 觸發程序 | dotnet add package Microsoft.Azure.WebJobs.Extensions.EventGrid |
參考連結