Azure.Messaging.EventGrid (.NET)
Biblioteca cliente para publicar eventos en temas, dominios y espacios de nombres de Azure Event Grid.
Instalación
dotnet add package Azure.Messaging.EventGrid
dotnet add package Azure.Messaging.EventGrid.Namespaces
dotnet add package Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents
Versión actual: 4.28.0 (estable)
Variables de Entorno
EVENT_GRID_TOPIC_ENDPOINT=https://<nombre-tema>.<region>.eventgrid.azure.net/api/events
EVENT_GRID_TOPIC_KEY=<clave-acceso>
EVENT_GRID_NAMESPACE_ENDPOINT=https://<espacio-nombres>.<region>.eventgrid.azure.net
EVENT_GRID_TOPIC_NAME=<nombre-tema>
EVENT_GRID_SUBSCRIPTION_NAME=<nombre-suscripción>
AZURE_TOKEN_CREDENTIALS=prod
Jerarquía de Clientes
Entrega Push (Temas/Dominios)
└── EventGridPublisherClient
├── SendEventAsync(EventGridEvent)
├── SendEventsAsync(IEnumerable<EventGridEvent>)
├── SendEventAsync(CloudEvent)
└── SendEventsAsync(IEnumerable<CloudEvent>)
Entrega Pull (Espacios de Nombres)
├── EventGridSenderClient
│ └── SendAsync(CloudEvent)
└── EventGridReceiverClient
├── ReceiveAsync()
├── AcknowledgeAsync()
├── ReleaseAsync()
└── RejectAsync()
Autenticación
Autenticación con Clave de API
using Azure;
using Azure.Messaging.EventGrid;
EventGridPublisherClient client = new(
new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
new AzureKeyCredential("<clave-acceso>"));
Credencial de Token de 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);
Autenticación con Token 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);
Publicación de Eventos
Esquema 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);
Esquema 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);
Publicación en un Dominio de 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);
Serialización Personalizada
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);
Entrega Pull (Espacios de Nombres)
Envío de Eventos a un Tema del Espacio de Nombres
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" })
});
Recepción y Procesamiento de Eventos
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($"Evento: {cloudEvent.Type}, Datos: {cloudEvent.Data}");
lockTokensToAck.Add(lockToken);
}
catch (Exception)
{
lockTokensToRelease.Add(lockToken);
}
}
if (lockTokensToAck.Any())
{
await receiverClient.AcknowledgeAsync(lockTokensToAck);
}
if (lockTokensToRelease.Any())
{
await receiverClient.ReleaseAsync(lockTokensToRelease);
}
Rechazo de Eventos (Dead Letter)
await receiverClient.RejectAsync(new[] { lockToken });
Consumo de Eventos (Azure Functions)
Desencadenador 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($"Tipo de evento: {eventGridEvent.EventType}");
log.LogInformation($"Asunto: {eventGridEvent.Subject}");
log.LogInformation($"Datos: {eventGridEvent.Data}");
}
}
Desencadenador 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($"Tipo de evento: {cloudEvent.Type}");
logger.LogInformation($"Fuente: {cloudEvent.Source}");
logger.LogInformation($"Datos: {cloudEvent.Data}");
}
}
Análisis de Eventos
Analizar 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 creado: {blobCreated.Url}");
break;
}
}
else
{
var customData = egEvent.Data.ToObjectFromJson<MyCustomData>();
}
}
Analizar CloudEvent
CloudEvent[] cloudEvents = CloudEvent.ParseMany(BinaryData.FromString(json));
foreach (CloudEvent cloudEvent in cloudEvents)
{
var data = cloudEvent.Data.ToObjectFromJson<MyEventData>();
Console.WriteLine($"Tipo: {cloudEvent.Type}, Datos: {data}");
}
Eventos del Sistema
using Azure.Messaging.EventGrid.SystemEvents;
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;
WebAppUpdatedEventData webAppUpdated;
ContainerRegistryImagePushedEventData imagePushed;
IotHubDeviceCreatedEventData deviceCreated;
Referencia de Tipos Clave
| Tipo | Propósito |
|---|
EventGridPublisherClient | Publicar en temas/dominios |
EventGridSenderClient | Enviar a temas del espacio de nombres |
EventGridReceiverClient | Recibir de suscripciones del espacio de nombres |
EventGridEvent | Esquema nativo de Event Grid |
CloudEvent | Esquema CloudEvents 1.0 |
ReceiveResult | Respuesta de entrega pull |
ReceiveDetails | Evento con propiedades del broker |
BrokerProperties | Token de bloqueo, contador de entregas |
Comparación de Esquemas de Eventos
| Característica | EventGridEvent | CloudEvent |
|---|
| Estándar | Específico de Azure | Estándar CNCF |
| Campos obligatorios | subject, eventType, dataVersion, data | source, type |
| Extensibilidad | Limitada | Atributos de extensión |
| Interoperabilidad | Solo Azure | Multiplataforma |
Buenas Prácticas
- Usar CloudEvents — Preferir CloudEvents para nuevas implementaciones (estándar de la industria)
- Agrupar eventos — Enviar múltiples eventos en una sola llamada para mayor eficiencia
- Usar Entra ID — Preferir identidad administrada sobre claves de acceso
- Manejadores idempotentes — Los eventos pueden entregarse más de una vez
- Configurar TTL del evento — Configurar el tiempo de vida para eventos del espacio de nombres
- Manejar fallos parciales — Confirmar/liberar eventos individualmente
- Usar dead-letter — Configurar dead-letter para eventos fallidos
- Validar esquemas — Validar los datos del evento antes de procesarlos
Manejo de Errores
using Azure;
try
{
await client.SendEventAsync(cloudEvent);
}
catch (RequestFailedException ex) when (ex.Status == 401)
{
Console.WriteLine("Autenticación fallida - verifique las credenciales");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
Console.WriteLine("Autorización fallida - verifique los permisos RBAC");
}
catch (RequestFailedException ex) when (ex.Status == 413)
{
Console.WriteLine("Carga útil demasiado grande - máximo 1 MB por evento, 1 MB total por lote");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error de Event Grid: {ex.Status} - {ex.Message}");
}
Patrón de Failover
try
{
var primaryClient = new EventGridPublisherClient(primaryUri, primaryKey);
await primaryClient.SendEventsAsync(events);
}
catch (RequestFailedException)
{
var secondaryClient = new EventGridPublisherClient(secondaryUri, secondaryKey);
await secondaryClient.SendEventsAsync(events);
}
SDKs Relacionados
| SDK | Propósito | Instalación |
|---|
Azure.Messaging.EventGrid | Temas/Dominios (este SDK) | dotnet add package Azure.Messaging.EventGrid |
Azure.Messaging.EventGrid.Namespaces | Entrega pull | dotnet add package Azure.Messaging.EventGrid.Namespaces |
Azure.Identity | Autenticación | dotnet add package Azure.Identity |
Microsoft.Azure.WebJobs.Extensions.EventGrid | Desencadenador de Azure Functions | dotnet add package Microsoft.Azure.WebJobs.Extensions.EventGrid |
Enlaces de Referencia