0Pricing
Cloud & IT Cert Prep · 课时

事件网格和事件驱动架构

使用事件网格路由来自 Azure 服务和自定义发布者的事件,将事件分发给多个订阅者,并比较事件网格、事件中心和服务总线。

事件网格和事件驱动架构 是 CoddyKit 上的免费 Cloud & IT Cert Prep 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Cloud & IT Cert Prep 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Cloud & IT Cert Prep 课程共包含 4 节课。

什么是事件驱动架构

在事件驱动架构中,组件通过发布和订阅事件进行通信,而不是直接相互调用。当发生值得关注的事情时,某个组件(生产者)会发出事件,例如上传文件、下单或设备发送读数。其他组件(订阅者)会独立、异步地响应它们关注的事件。这种方式将生产者与使用者解耦,从而提高可伸缩性、复原能力和可维护性。

什么是 Azure Event Grid

Azure Event Grid 是一种完全托管的事件路由服务,使用推送模型将事件从源(发布者)传送到处理程序(订阅者)。Event Grid 专为反应式离散事件而设计,即某些内容发生变化,您需要立即做出响应。它通过自动重试保证至少一次传递,支持筛选以便订阅者只接收相关事件,还可以将事件路由到 Azure Function、Logic Apps、Webhook、Event Hubs 和 Service Bus 队列。

Event Grid 主题和事件订阅

发布者会将事件发送到Event Grid 主题。订阅者在主题上创建事件订阅,并指定终结点和可选的筛选规则。单个主题可以有多个订阅,每个订阅都会收到匹配事件的独立副本。Blob Storage、Resource Manager、Service Bus 和Azure Container Registry等 Azure 服务都是内置事件源,并提供无需额外配置的系统主题。

# Create a custom Event Grid topic
az eventgrid topic create \
  --name MyEventTopic \
  --resource-group MyRG \
  --location eastus

# Create a subscription routing to an Azure Function
az eventgrid event-subscription create \
  --name myFunctionSub \
  --source-resource-id '/subscriptions/.../providers/Microsoft.EventGrid/topics/MyEventTopic' \
  --endpoint '/subscriptions/.../providers/Microsoft.Web/sites/myFunctionApp/functions/EventHandler'

事件架构

发布到 Event Grid 的事件遵循标准 JSON 架构,并包含以下必需字段:id(唯一标识符)、eventType(例如 Microsoft.Storage.BlobCreated)、subject(事件资源的路径)、eventTime(ISO 8601 时间戳)、dataVersion 和 data(特定于事件的 payload)。Event Grid 还支持CloudEvents 架构(CNCF 标准),以便与其他事件平台实现互操作。

// Event Grid event payload (Event Grid schema)
[
  {
    'id': 'b781910b-3000-4f19-a4c2-b6b9c4ca7a12',
    'eventType': 'Microsoft.Storage.BlobCreated',
    'subject': '/blobServices/default/containers/uploads/blobs/photo.jpg',
    'eventTime': '2025-01-15T12:30:00.000Z',
    'data': {
      'api': 'PutBlockList',
      'url': 'https://mystorageacct.blob.core.windows.net/uploads/photo.jpg',
      'contentType': 'image/jpeg',
      'contentLength': 524288
    },
    'dataVersion': '',
    'metadataVersion': '1'
  }
]

事件筛选

事件订阅支持筛选,以减少订阅者端收到的噪声。您可以按事件类型筛选(只接收 BlobCreated,不接收 BlobDeleted)、按主题前缀或后缀筛选(只接收特定容器中的 Blob),或者使用 StringContains、NumberGreaterThan 和 BoolEquals 等运算符,对事件数据中的任意字段应用高级筛选。筛选在服务器端进行,因此订阅者只会收到符合其条件的事件。

# Subscribe to BlobCreated events for .jpg files only
az eventgrid event-subscription create \
  --name jpgImageSub \
  --source-resource-id '/subscriptions/.../storageAccounts/mystorageaccount' \
  --endpoint 'https://myfunction.azurewebsites.net/api/ProcessImage' \
  --included-event-types 'Microsoft.Storage.BlobCreated' \
  --subject-ends-with '.jpg'

Event Grid、Event Hubs 与 Service Bus 的比较

Azure 提供三种处理事件和消息的服务,请根据您的场景进行选择。Event Grid 用于反应式事件路由(低容量、离散且反应式,例如资源变更通知)。Event Hubs 用于高吞吐量事件流(每秒数百万个事件、遥测数据、大数据管道)。Service Bus 用于企业消息传递,支持排序、重复数据删除、死信和事务(订单处理、金融交易)。

// Decision guide:
// Event Grid  — 'Something happened, react to it'
//               Azure resource events, webhooks, low-latency fan-out
//               Price: per event (cheap for low volume)

// Event Hubs  — 'Capture a firehose of streaming data'
//               IoT telemetry, log aggregation, real-time analytics
//               Price: per throughput unit + capture

// Service Bus — 'Reliable message delivery between services'
//               Order processing, workflow steps, dead-letter queues
//               Price: per operation + messaging units

发布自定义事件

使用包含主题访问密钥的简单 HTTP POST 请求,将自定义事件发布到 Event Grid 主题。任何能够发出 HTTP 请求的服务或应用程序都可以发布事件。因此,您可以轻松地从本地应用程序、第三方服务或不原生支持 Event Grid 的 Azure 服务发出事件。为提高效率,每次 POST 最多可以批量发送 1 MB 的事件。

# Get the topic endpoint and key
TOPIC_ENDPOINT=$(az eventgrid topic show --name MyEventTopic --resource-group MyRG --query endpoint -o tsv)
TOPIC_KEY=$(az eventgrid topic key list --name MyEventTopic --resource-group MyRG --query key1 -o tsv)

# Publish a custom event
curl -X POST $TOPIC_ENDPOINT \
  -H 'Content-Type: application/json' \
  -H "aeg-sas-key: $TOPIC_KEY" \
  -d '[{
    "id": "event-001",
    "eventType": "Contoso.OrderPlaced",
    "subject": "/orders/ORD-12345",
    "eventTime": "2025-01-15T12:00:00Z",
    "data": { "orderId": "ORD-12345", "total": 99.99 },
    "dataVersion": "1.0"
  }]'

死信和重试策略

如果事件传递尝试失败(订阅者返回非 2xx HTTP 响应),Event Grid 会使用带抖动的指数退避策略进行重试,最长持续24 小时(可配置为最长 72 小时),最多重试 30 次。重试次数用尽后,Event Grid 可以将无法传递的事件转入死信,发送到 Azure Blob Storage 容器,以便手动调查。当可靠的事件传递至关重要,并且您需要审计或重新处理失败事件时,请配置死信功能。

# Configure dead-letter storage and retry for a subscription
az eventgrid event-subscription update \
  --name myFunctionSub \
  --source-resource-id '/subscriptions/.../topics/MyEventTopic' \
  --deadletter-endpoint '/subscriptions/.../storageAccounts/mystg/blobServices/default/containers/deadletter' \
  --max-delivery-attempts 30 \
  --event-ttl 1440  # 24 hours in minutes

Azure Event Hubs 概述

Azure Event Hubs 是一个分布式数据流平台,每秒能够接收和处理数百万个事件。它采用分区使用者模型:事件会分布到各个分区,每个使用者组都能按照自己的速率独立读取事件。这样,多个使用者无需协调即可处理同一数据流。常见使用场景包括 IoT 遥测数据摄取、应用程序日志聚合、点击流分析以及实时仪表板数据管道。

# Create an Event Hubs namespace and hub
az eventhubs namespace create \
  --name myEventHubNS \
  --resource-group MyRG \
  --location eastus \
  --sku Standard

az eventhubs eventhub create \
  --name telemetry \
  --namespace-name myEventHubNS \
  --resource-group MyRG \
  --partition-count 8 \
  --message-retention 3  # Days to retain events

用于可靠消息传递的 Azure Service Bus

Azure Service Bus 是一种企业消息代理,提供队列(点对点)以及带订阅的主题(发布-订阅)。与 Event Grid(即发即忘)和 Event Hubs(流式处理)不同,Service Bus 保证有序传递(FIFO 队列)、支持重复消息检测、为处理失败提供死信队列、支持用于分组处理的消息会话以及事务,这些功能对于金融和订单处理工作流都至关重要。

# Create a Service Bus namespace and queue
az servicebus namespace create \
  --name myServiceBusNS \
  --resource-group MyRG \
  --location eastus \
  --sku Standard

az servicebus queue create \
  --name order-processing \
  --namespace-name myServiceBusNS \
  --resource-group MyRG \
  --enable-dead-lettering-on-message-expiration true \
  --max-delivery-count 10  # Move to dead-letter after 10 failed attempts

实用的事件驱动模式:文件处理

一种常见的 Azure 事件驱动模式是:用户将文件上传到Blob Storage,Blob Storage 向Event Grid触发 BlobCreated 事件。Event Grid 将事件路由到Azure Function,由其处理文件(调整图像大小、提取文本、验证数据),然后将结果写入Azure SQL Database。如果处理失败,事件会被转入存储容器中的死信。整个管道无需轮询,空闲时也不需要持久运行的计算资源。

// Azure Function: process image on BlobCreated event
module.exports = async function (context, eventGridEvent) {
  const blobUrl = eventGridEvent.data.url;
  const blobName = eventGridEvent.subject.split('/blobs/').pop();

  context.log('Processing image:', blobName);

  // Process via Cognitive Services Vision API
  const tags = await analyzeImage(blobUrl);

  // Write metadata to Cosmos DB via output binding
  context.bindings.cosmosOutput = {
    id: blobName,
    tags,
    processedAt: new Date().toISOString()
  };

  context.log('Processing complete for:', blobName);
};

快速检查

测试您对本课 Microsoft Azure 基础知识(AZ-900)概念的理解。

课程回顾

在本课中,您学习了以下内容:Azure Event Grid通过推送传递、筛选和死信,将离散事件从发布者路由到订阅者;了解了Event Grid(反应式事件)、Event Hubs(流式处理)和Service Bus(可靠的企业消息传递)之间的主要区别;还学习了如何将 Blob Storage 事件通过 Event Grid 链接到 Azure Function,构建事件驱动管道。接下来,我们将探索 Azure DevOps 服务。

常见问题解答

「事件网格和事件驱动架构」课时是免费的吗?

是的 — 「事件网格和事件驱动架构」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Cloud & IT Cert Prep 课程的其余内容,请升级到 CoddyKit PRO。 Cloud & IT Cert Prep 课程共包含 4 节课。

「事件网格和事件驱动架构」这节课中我会学到什么?

使用事件网格路由来自 Azure 服务和自定义发布者的事件,将事件分发给多个订阅者,并比较事件网格、事件中心和服务总线。 你通过在浏览器中直接运行的动手代码来练习 Cloud & IT Cert Prep,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Cloud & IT Cert Prep 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Cloud & IT Cert Prep 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「事件网格和事件驱动架构」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Cloud & IT Cert Prep 课中编写并运行代码吗?

能。每节 Cloud & IT Cert Prep 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Azure Functions 触发器和绑定
  2. 使用 Durable Functions 编排有状态工作流
  3. Azure Logic Apps
  4. 事件网格和事件驱动架构
← 返回 Cloud & IT Cert Prep