将 CloudEvents v1.0 架构与事件网格配合使用Use CloudEvents v1.0 schema with Event Grid

除了采用默认事件架构的事件,Azure 事件网格本身还支持采用 CloudEvents v1.0 的 JSON 架构HTTP 协议绑定的事件。In addition to its default event schema, Azure Event Grid natively supports events in the JSON implementation of CloudEvents v1.0 and HTTP protocol binding. CloudEvents 是一种用于描述事件数据的开放规范CloudEvents is an open specification for describing event data.

CloudEvents 提供的常用事件架构适合发布和使用基于云的事件,因此可简化互操作性。CloudEvents simplifies interoperability by providing a common event schema for publishing, and consuming cloud based events. 可以通过此架构使用统一的工具、以标准方式路由和处理事件,以及以通用方式反序列化外部事件架构。This schema allows for uniform tooling, standard ways of routing & handling events, and universal ways of deserializing the outer event schema. 使用通用架构可以更轻松地跨平台集成工作。With a common schema, you can more easily integrate work across platforms.

CloudEvents 是由包括 Microsoft 在内的多个协作者通过 Cloud Native Computing Foundation 构建的。CloudEvents is being built by several collaborators, including Microsoft, through the Cloud Native Computing Foundation. 它目前的发布版本为 1.0。It's currently available as version 1.0.

本文介绍如何将 CloudEvents 架构与事件网格配合使用。This article describes how to use the CloudEvents schema with Event Grid.

重要

使用 PowerShell 的 Azure 功能必须已安装 AzureRM 模块。Using this Azure feature from PowerShell requires the AzureRM module installed. 该模块是旧模块,仅适用于 Windows PowerShell 5.1,它不再接收新功能。This is an older module only available for Windows PowerShell 5.1 that no longer receives new features. 针对相同版本的 PowerShell 进行安装时,AzAzureRM 模块不兼容。The Az and AzureRM modules are not compatible when installed for the same versions of PowerShell. 如果需要两个版本,请执行以下操作:If you need both versions:

  1. 在 PowerShell 5.1 会话中卸载 Az 模块Uninstall the Az module from a PowerShell 5.1 session.
  2. 在 PowerShell 5.1 会话中安装 AzureRM 模块Install the AzureRM module from a PowerShell 5.1 session.
  3. 下载并安装 PowerShell Core 6.x 或更高版本Download and install PowerShell Core 6.x or later.
  4. 在 PowerShell Core 会话中安装 Az 模块Install the Az module in a PowerShell Core session.

安装预览功能Install preview feature

此功能为预览版。This feature is in preview. 若要使用它,必须安装预览扩展或模块。To use it, you must install a preview extension or module.

安装适用于 Azure CLI 的扩展Install extension for Azure CLI

对于 Azure CLI,需要事件网格扩展For Azure CLI, you need the Event Grid extension.

对于本地安装:For a local installation:

  1. 在本地卸载 Azure CLI。Uninstall Azure CLI locally.
  2. 安装最新版本的 Azure CLI。Install the latest version of Azure CLI.
  3. 启动命令窗口。Launch command window.
  4. 卸载早期版本的扩展 az extension remove -n eventgridUninstall previous versions of the extension az extension remove -n eventgrid
  5. 安装扩展 az extension add -n eventgridInstall the extension az extension add -n eventgrid

安装适用于 PowerShell 的模块Install module for PowerShell

对于 PowerShell,需要 AzureRM.EventGrid 模块For PowerShell, you need the AzureRM.EventGrid module.

对于本地安装:For a local installation:

  1. 以管理员身份打开 PowerShell 控制台Open PowerShell console as administrator
  2. 安装模块 Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGalleryInstall the module Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery

如果 -AllowPrerelease 参数不可用,请使用以下步骤:If the -AllowPrerelease parameter isn't available, use the following steps:

  1. 运行 Install-Module PowerShellGet -ForceRun Install-Module PowerShellGet -Force
  2. 运行 Update-Module PowerShellGetRun Update-Module PowerShellGet
  3. 关闭 PowerShell 控制台Close the PowerShell console
  4. 以管理员身份重启 PowerShellRestart PowerShell as administrator
  5. 安装模块 Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGalleryInstall the module Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery

CloudEvent 架构CloudEvent schema

下面以示例方式说明了 CloudEvents 格式的 Azure Blob 存储事件:Here is an example of an Azure Blob Storage event in CloudEvents format:

{
    "specversion": "1.0",
    "type": "Microsoft.Storage.BlobCreated",  
    "source": "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.Storage/storageAccounts/{storage-account}",
    "id": "9aeb0fdf-c01e-0131-0922-9eb54906e209",
    "time": "2019-11-18T15:13:39.4589254Z",
    "subject": "blobServices/default/containers/{storage-container}/blobs/{new-file}",
    "dataschema": "#",
    "data": {
        "api": "PutBlockList",
        "clientRequestId": "4c5dd7fb-2c48-4a27-bb30-5361b5de920a",
        "requestId": "9aeb0fdf-c01e-0131-0922-9eb549000000",
        "eTag": "0x8D76C39E4407333",
        "contentType": "image/png",
        "contentLength": 30699,
        "blobType": "BlockBlob",
        "url": "https://gridtesting.blob.core.chinacloudapi.cn/testcontainer/{new-file}",
        "sequencer": "000000000000000000000000000099240000000000c41c18",
        "storageDiagnostics": {
            "batchId": "681fe319-3006-00a8-0022-9e7cde000000"
        }
    }
}

此处提供 CloudEvents v1.0 中的可用字段、类型和定义的详细说明。A detailed description of the available fields, their types, and definitions in CloudEvents v1.0 is available here.

在 CloudEvents 架构和事件网格架构中传递的事件的标头值是相同的,但 content-type 除外。The headers values for events delivered in the CloudEvents schema and the Event Grid schema are the same except for content-type. 对于 CloudEvents 架构,该标头值为 "content-type":"application/cloudevents+json; charset=utf-8"For CloudEvents schema, that header value is "content-type":"application/cloudevents+json; charset=utf-8". 对于事件网格架构,该标头值为 "content-type":"application/json; charset=utf-8"For Event Grid schema, that header value is "content-type":"application/json; charset=utf-8".

为 CloudEvents 配置事件网格Configure Event Grid for CloudEvents

可以将事件网格用于 CloudEvents 架构的事件的输入和输出。You can use Event Grid for both input and output of events in CloudEvents schema. 可以将 CloudEvents 用于系统事件(例如 Blob 存储事件和 IoT 中心事件)和自定义事件。You can use CloudEvents for system events, like Blob Storage events and IoT Hub events, and custom events. 它还可以将网络上的这些事件来回转换。It can also transform those events on the wire back and forth.

输入架构Input schema 输出架构Output schema
CloudEvents 格式CloudEvents format CloudEvents 格式CloudEvents format
事件网格格式Event Grid format CloudEvents 格式CloudEvents format
事件网格格式Event Grid format 事件网格格式Event Grid format

对于所有事件架构,事件网格都要求在发布到事件网格主题时以及在创建事件订阅时进行验证。For all event schemas, Event Grid requires validation when publishing to an event grid topic and when creating an event subscription. 有关详细信息,请参阅事件网格安全性和身份验证For more information, see Event Grid security and authentication.

输入架构Input schema

在创建自定义主题时为自定义主题设置输入架构。You set the input schema for a custom topic when you create the custom topic.

对于 Azure CLI,请使用:For Azure CLI, use:

# If you have not already installed the extension, do it now.
# This extension is required for preview features.
az extension add --name eventgrid

az eventgrid topic create \
  --name <topic_name> \
  -l chinaeast \
  -g gridResourceGroup \
  --input-schema cloudeventschemav1_0

对于 PowerShell,请使用:For PowerShell, use:

# If you have not already installed the module, do it now.
# This module is required for preview features.
Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery

New-AzureRmEventGridTopic `
  -ResourceGroupName gridResourceGroup `
  -Location chinaeast `
  -Name <topic_name> `
  -InputSchema CloudEventSchemaV1_0

输出架构Output schema

在创建事件订阅时设置输出架构。You set the output schema when you create the event subscription.

对于 Azure CLI,请使用:For Azure CLI, use:

topicID=$(az eventgrid topic show --name <topic-name> -g gridResourceGroup --query id --output tsv)

az eventgrid event-subscription create \
  --name <event_subscription_name> \
  --source-resource-id $topicID \
  --endpoint <endpoint_URL> \
  --event-delivery-schema cloudeventschemav1_0

对于 PowerShell,请使用:For PowerShell, use:

$topicid = (Get-AzureRmEventGridTopic -ResourceGroupName gridResourceGroup -Name <topic-name>).Id

New-AzureRmEventGridSubscription `
  -ResourceId $topicid `
  -EventSubscriptionName <event_subscription_name> `
  -Endpoint <endpoint_URL> `
  -DeliverySchema CloudEventSchemaV1_0

目前,在以 CloudEvents 架构传递事件时,无法为 Azure Functions 应用使用事件网格触发器。Currently, you can't use an Event Grid trigger for an Azure Functions app when the event is delivered in the CloudEvents schema. 使用 HTTP 触发器。Use an HTTP trigger. 有关实现在 CloudEvents 架构中接收事件的 HTTP 触发器的示例,请参阅将 CloudEvents 与 Azure Functions 配合使用For examples of implementing an HTTP trigger that receives events in the CloudEvents schema, see Using CloudEvents with Azure Functions.

使用 CloudEvents v1.0 验证终结点Endpoint Validation with CloudEvents v1.0

如果熟悉事件网格,你可能会了解事件网格的用于防止滥用的终结点验证握手。If you are already familiar with Event Grid, you may be aware of Event Grid's endpoint validation handshake for preventing abuse. CloudEvents v1.0 使用 HTTP OPTIONS 方法实现自己的滥用保护语义CloudEvents v1.0 implements its own abuse protection semantics using the HTTP OPTIONS method. 可以在 此处阅读详细内容。You can read more about it here. 使用 CloudEvents 架构进行输出时,事件网格可与 CloudEvents v1.0 滥用保护配合使用,取代事件网格验证事件机制。When using the CloudEvents schema for output, Event Grid uses with the CloudEvents v1.0 abuse protection in place of the Event Grid validation event mechanism.

与 Azure Functions 配合使用Use with Azure Functions

Azure Functions 事件网格绑定本身不支持 CloudEvents,因此使用 HTTP 触发的函数读取 CloudEvents 消息。The Azure Functions Event Grid binding does not natively support CloudEvents, so HTTP-triggered functions are used to read CloudEvents messages. 使用 HTTP 触发器读取 CloudEvents 时,必须编写代码来指定事件网格触发器自动执行的操作:When using an HTTP trigger to read CloudEvents, you have to write code for what the Event Grid trigger does automatically:

  • 将验证响应发送到订阅验证请求Sends a validation response to a subscription validation request.
  • 针对请求正文中包含的事件数组的每个元素调用该函数一次。Invokes the function once per element of the event array contained in the request body.

有关用于在本地调用函数或者在 Azure 中运行函数的 URL 的信息,请参阅 HTTP 触发器绑定参考文档For information about the URL to use for invoking the function locally or when it runs in Azure, see the HTTP trigger binding reference documentation

以下 HTTP 触发器的示例 C# 代码可模拟事件网格触发器的行为。The following sample C# code for an HTTP trigger simulates Event Grid trigger behavior. 将此示例用于以 CloudEvents 架构传递的事件。Use this example for events delivered in the CloudEvents schema.

[FunctionName("HttpTrigger")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "options", Route = null)]HttpRequestMessage req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    if (req.Method == "OPTIONS")
    {
        // If the request is for subscription validation, send back the validation code
        
        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Add("Webhook-Allowed-Origin", "eventgrid.chinacloudapi.cn");

        return response;
    }

    var requestmessage = await req.Content.ReadAsStringAsync();
    var message = JToken.Parse(requestmessage);

    // The request is not for subscription validation, so it's for an event.
    // CloudEvents schema delivers one event at a time.
    log.LogInformation($"Source: {message["source"]}");
    log.LogInformation($"Time: {message["eventTime"]}");
    log.LogInformation($"Event data: {message["data"].ToString()}");

    return req.CreateResponse(HttpStatusCode.OK);
}

以下 HTTP 触发器的示例 JavaScript 代码可模拟事件网格触发器的行为。The following sample JavaScript code for an HTTP trigger simulates Event Grid trigger behavior. 将此示例用于以 CloudEvents 架构传递的事件。Use this example for events delivered in the CloudEvents schema.

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    
    if (req.method == "OPTIONS") {
        // If the request is for subscription validation, send back the validation code
        
        context.log('Validate request received');
        context.res = { status: 200 };
        context.res.headers.append('Webhook-Allowed-Origin', 'eventgrid.chinacloudapi.cn');
    }
    else
    {
        var message = req.body;
        
        // The request is not for subscription validation, so it's for an event.
        // CloudEvents schema delivers one event at a time.
        var event = JSON.parse(message);
        context.log('Source: ' + event.source);
        context.log('Time: ' + event.eventTime);
        context.log('Data: ' + JSON.stringify(event.data));
    }
 
    context.done();
};

后续步骤Next steps