搭配使用 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 and handling events, and universal ways of deserializing the outer event schema. 透過通用結構描述,您將可更輕鬆地跨平台整合工作。With a common schema, you can more easily integrate work across platforms.

目前有數個共同作業者 (包括 Microsoft) 正透過 Cloud Native Computing Foundation 建置 CloudEvents。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.

CloudEvent 結構描述CloudEvent schema

以下是 CloudEvents 格式的 Azure Blob 儲存體事件範例:Here's 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.windows.net/testcontainer/{new-file}",
        "sequencer": "000000000000000000000000000099240000000000c41c18",
        "storageDiagnostics": {
            "batchId": "681fe319-3006-00a8-0022-9e7cde000000"
        }
    }
}

如需可用欄位、其類型和定義的詳細描述,請參閱 CloudEventsv1.0。For a detailed description of the available fields, their types, and definitions, see CloudEvents v1.0.

在 CloudEvents 結構描述中傳遞的事件標頭值與事件方格結構描述的該值相同,不同之處在於 content-typeThe 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 the CloudEvents schema, that header value is "content-type":"application/cloudevents+json; charset=utf-8". 針對事件方格架構,該標頭值為 "content-type":"application/json; charset=utf-8"For the 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 the CloudEvents schema. 下表描述可能的轉換:The following table describes the possible transformations:

事件方格資源Event Grid resource 輸入結構描述Input schema 傳遞架構Delivery schema
系統主題System topics 事件格線結構描述Event Grid schema 事件方格架構或 CloudEvents 架構Event Grid schema or CloudEvents schema
自訂主題/網域Custom topics/domains 事件格線結構描述Event Grid schema 事件方格架構或 CloudEvents 架構Event Grid schema or CloudEvents schema
自訂主題/網域Custom topics/domains CloudEvents 結構描述CloudEvents schema CloudEvents 結構描述CloudEvents schema
自訂主題/網域Custom topics/domains 自訂架構Custom schema 自訂架構、事件方格架構或 CloudEvents 架構Custom schema, Event Grid schema, or CloudEvents schema
合作夥伴主題Partner topics CloudEvents 結構描述CloudEvents schema CloudEvents 結構描述CloudEvents schema

針對所有事件架構,當您發佈至事件方格主題以及建立事件訂閱時,事件方格需要驗證。For all event schemas, Event Grid requires validation when you're publishing to an Event Grid topic and when you're creating an event subscription.

如需詳細資訊,請參閱 Event Grid 安全性和驗證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 the Azure CLI, use:

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

對於 PowerShell,請使用:For PowerShell, use:

New-AzEventGridTopic `
  -ResourceGroupName gridResourceGroup `
  -Location westcentralus `
  -Name <topic_name> `
  -InputSchema CloudEventSchemaV1_0

輸出結構描述Output schema

當您建立事件訂用帳戶時,您可以設定輸出結構描述。You set the output schema when you create the event subscription.

針對 Azure CLI,請使用:For the 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-AzEventGridTopic -ResourceGroupName gridResourceGroup -Name <topic-name>).Id

New-AzEventGridSubscription `
  -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. 如需實作 HTTP 觸發程序 (該觸發程序會接收 CloudEvents 結構描述中的事件) 的範例,請參閱搭配使用 CloudEvents 與 Azure FunctionsFor 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're already familiar with Event Grid, you might be aware of the endpoint validation handshake for preventing abuse. CloudEvents v1.0 藉由使用 HTTP OPTIONS 方法,來實行自己的 濫用保護語義CloudEvents v1.0 implements its own abuse protection semantics by using the HTTP OPTIONS method. 若要閱讀詳細資訊,請參閱 適用于事件傳遞的 HTTP 1.1 Web 勾點-版本 1.0To read more about it, see HTTP 1.1 Web Hooks for event delivery - Version 1.0. 當您使用 CloudEvents 架構進行輸出時,事件方格會使用 CloudEvents v1.0 的濫用保護來取代事件方格驗證事件機制。When you use the CloudEvents schema for output, Event Grid uses 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 doesn't natively support CloudEvents, so HTTP-triggered functions are used to read CloudEvents messages. 當您使用 HTTP 觸發程式來讀取 CloudEvents 時,您必須撰寫事件方格觸發程式自動執行的程式碼:When you use 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, "post", "options", Route = null)]HttpRequestMessage req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    if (req.Method == HttpMethod.Options)
    {
        // If the request is for subscription validation, send back the validation code
        
        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Webhook-Allowed-Origin", "eventgrid.azure.net");

        return response;
    }

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

    // The request isn't 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,
            headers: {
                'Webhook-Allowed-Origin': 'eventgrid.azure.net',
            },
         };
    }
    else
    {
        var message = req.body;
        
        // The request isn't 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