快速入门:使用事件网格将自定义事件路由到 Azure 函数Quickstart: Route custom events to an Azure Function with Event Grid

Azure 事件网格是针对云的事件处理服务。Azure Event Grid is an eventing service for the cloud. Azure 函数是受支持的事件处理程序之一。Azure Functions is one of the supported event handlers. 在本文中,将使用 Azure 门户创建一个自定义主题,然后订阅该自定义主题,再触发可查看结果的事件。In this article, you use the Azure portal to create a custom topic, subscribe to the custom topic, and trigger the event to view the result. 将事件发送至 Azure 函数。You send the events to an Azure Function.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

创建 Azure 函数Create Azure Function

在订阅自定义主题之前,创建一个函数来处理事件。Before subscribing to the custom topic, create a function to handle the events.

  1. 按照创建函数应用中的说明创建函数应用。Create a function app using instructions from Create a function app.

  2. 使用事件网格触发器创建函数。Create a function using the Event Grid Trigger. 如果这是你第一次使用此触发器,可能需要单击“安装”来安装该扩展。Select If this is your first time using this trigger, you may have to click 'Install' to install the extension.

    1. 在“函数应用”页上,选择左侧菜单上的“Functions”,在模板中搜索“事件网格”,然后选择“Azure 事件网格触发器”。On the Function App page, select Functions on the left menu, search for Event Grid in templates, and then select Azure Event Grid trigger.

      选择事件网格触发器

  3. 在“新建函数”页上,输入函数名称,然后选择“创建函数”。On the New Function page, enter a name for the function, and select Create Function.

    “新建函数”页

  4. 使用“代码 + 测试”页可以查看函数的现有代码并对其进行更新。Use the Code + Test page to see the existing code for the function and update it.

启用事件网格资源提供程序Enable Event Grid resource provider

如果以前未在 Azure 订阅中使用过事件网格,则可能需要注册事件网格资源提供程序。If you haven't previously used Event Grid in your Azure subscription, you may need to register the Event Grid resource provider.

在 Azure 门户中:In the Azure portal:

  1. 选择 订阅Select Subscriptions.
  2. 选择要用于事件网格的订阅。Select the subscription you're using for Event Grid.
  3. 在“设置”下,选择“资源提供程序”。Under Settings, select Resource providers.
  4. 找到 Microsoft.EventGridFind Microsoft.EventGrid.
  5. 如果尚未注册,请选择“注册”。If not registered, select Register.

完成注册可能需要一些时间。It may take a moment for the registration to finish. 选择“刷新”可更新状态。Select Refresh to update the status. 当“状态”为“已注册”后,即可继续。When Status is Registered, you're ready to continue.

创建自定义主题Create a custom topic

事件网格主题提供用户定义的终结点,可向其发布事件。An event grid topic provides a user-defined endpoint that you post your events to.

  1. 登录到 Azure 门户Sign in to Azure portal.

  2. 在左侧导航菜单中选择“所有服务”,搜索“事件网格”,然后选择“事件网格主题”。 Select All services on the left navigational menu, search for Event Grid, and select Event Grid Topics.

    选择“事件网格主题”

  3. 在“事件网格主题”页上的工具栏中选择“添加”。 On the Event Grid Topics page, select + Add on the toolbar.

    “添加事件网格主题”按钮

  4. 在“创建主题”页上执行以下步骤: On the Create Topic page, follow these steps:

    1. 为自定义主题提供唯一的 名称Provide a unique name for the custom topic. 主题名称必须唯一,因为它由 DNS 条目表示。The topic name must be unique because it's represented by a DNS entry. 请不要使用图中所示的名称。Don't use the name shown in the image. 而是创建自己的名称 - 它必须介于 3 到 50 个字符之间,并且只包含值 a-z、A-Z、0-9 和“-”。Instead, create your own name - it must be between 3-50 characters and contain only values a-z, A-Z, 0-9, and "-".

    2. 选择 Azure 订阅Select your Azure subscription.

    3. 选择与前面的步骤一致的资源组。Select the same resource group from the previous steps.

    4. 选择事件网格主题的 位置Select a location for the event grid topic.

    5. 在“事件架构”字段中,保留默认值“事件网格架构”。 Keep the default value Event Grid Schema for the Event Schema field.

      “创建主题”页

    6. 选择“创建” 。Select Create.

  5. 创建自定义主题后,将会看到成功通知。After the custom topic has been created, you see the successful notification. 选择“转到资源组”。 Select Go to resource group.

    看到成功通知

  6. 在“资源组”页上,选择事件网格主题。 On the Resource Group page, select the event grid topic.

    选择事件网格主题资源

  7. 此时会显示事件网格的“事件网格主题”页。 You see the Event Grid Topic page for your event grid. 请将此页保持打开状态,Keep this page open. 稍后在本快速入门中需要使用此页。You use it later in the quickstart.

    “事件网格主题”主页

订阅自定义主题Subscribe to custom topic

订阅事件网格主题,以告知事件网格要跟踪哪些事件,以及要将事件发送到何处。You subscribe to an event grid topic to tell Event Grid which events you want to track, and where to send the events.

  1. 现在,请在自定义主题的“事件网格主题”页上的工具栏中,选择“+ 事件订阅”。 Now, on the Event Grid Topic page for your custom topic, select + Event Subscription on the toolbar.

    添加事件订阅

  2. 在“创建事件订阅”页上执行以下步骤: On the Create Event Subscription page, follow these steps:

    1. 输入事件订阅的“名称” 。Enter a name for the event subscription.

    2. 选择“Azure 函数”作为“终结点类型” 。Select Azure Function for the Endpoint type.

    3. 选择“选择终结点”。 Choose Select an endpoint.

      提供事件订阅值

    4. 对于函数终结点,选择你的函数应用所在的 Azure 订阅和资源组,然后选择之前创建的函数应用和函数。For the function endpoint, select the Azure Subscription and Resource Group your Function App is in and then select the Function App and function you created earlier. 选择“确认所选内容” 。Select Confirm Selection.

      提供终结点 URL

    5. 此步骤是可选的,但建议在生产方案中使用。This step is optional, but recommended for production scenarios. 在“创建事件订阅”页上,切换到“高级功能”选项卡,并设置“每批最大事件数”和“首选批大小(KB)”的值。On the Create Event Subscription page, switch to the Advanced Features tab, and set values for Max events per batch and Preferred batch size in kilobytes.

      批处理可提高吞吐量。Batching can give you high-throughput. 对于“每批最大事件数”,请设置订阅要在一个批中包含的事件的最大数目。For Max events per batch, set maximum number of events that a subscription will include in a batch. 首选批大小设置批大小的首选上限(以 KB 为单位),但如果单个事件大于此阈值,则可以超出此上限。Preferred batch size sets the preferred upper bound of batch size in kilo bytes, but can be exceeded if a single event is larger than this threshold.

      启用批处理

    6. 在“创建事件订阅”页上,选择“创建”。 On the Create Event Subscription page, select Create.

向主题发送事件Send an event to your topic

现在,让我们触发一个事件,看事件网格如何将消息分发到终结点。Now, let's trigger an event to see how Event Grid distributes the message to your endpoint. 使用 Azure CLI 或 PowerShell 向自定义主题发送测试性事件。Use either Azure CLI or PowerShell to send a test event to your custom topic. 通常情况下,应用程序或 Azure 服务会发送事件数据。Typically, an application or Azure service would send the event data.

第一个示例使用 Azure CLI。The first example uses Azure CLI. 它获取自定义主题的 URL 和密钥,以及示例事件数据。It gets the URL and key for the custom topic, and sample event data. 将自定义主题名称用于 <topic name>Use your custom topic name for <topic name>. 它将创建示例事件数据。It creates sample event data. JSON 的 data 元素是事件的有效负载。The data element of the JSON is the payload of your event. 可以将任何格式正确的 JSON 置于此字段中。Any well-formed JSON can go in this field. 也可将主题字段用于高级路由和筛选。You can also use the subject field for advanced routing and filtering. CURL 是发送 HTTP 请求的实用工具。CURL is a utility that sends HTTP requests.

Azure CLIAzure CLI

  1. 运行以下命令以获取主题的 终结点:复制并粘贴该命令后,更新 主题名称资源组名称,然后运行该命令。Run the following command to get the endpoint for the topic: After you copy and paste the command, update the topic name and resource group name before you run the command.

    endpoint=$(az eventgrid topic show --name <topic name> -g <resource group name> --query "endpoint" --output tsv)
    
  2. 运行以下命令以获取自定义主题的 密钥:复制并粘贴该命令后,更新 主题名称资源组名称,然后运行该命令。Run the following command to get the key for the custom topic: After you copy and paste the command, update the topic name and resource group name before you run the command.

    key=$(az eventgrid topic key list --name <topic name> -g <resource group name> --query "key1" --output tsv)
    
  3. 复制以下包含事件定义的语句,然后按 ENTERCopy the following statement with the event definition, and press ENTER.

    event='[ {"id": "'"$RANDOM"'", "eventType": "recordInserted", "subject": "myapp/vehicles/motorcycles", "eventTime": "'`date +%Y-%m-%dT%H:%M:%S%z`'", "data":{ "make": "Ducati", "model": "Monster"},"dataVersion": "1.0"} ]'
    
  4. 运行以下 Curl 命令以发布事件:Run the following Curl command to post the event:

    curl -X POST -H "aeg-sas-key: $key" -d "$event" $endpoint
    

Azure PowerShellAzure PowerShell

第二个示例使用 PowerShell,执行的步骤类似。The second example uses PowerShell to perform similar steps.

  1. 设置以下变量。Set the following variables. 复制并粘贴每个命令后,更新 主题名称资源组名称,然后运行该命令:After you copy and paste each command, update the topic name and resource group name before you run the command:

    $resourceGroupName = <resource group name>
    $topicName = <topic name>
    
  2. 运行以下命令以获取主题的 终结点密钥Run the following commands to get the endpoint and the keys for the topic:

    $endpoint = (Get-AzEventGridTopic -ResourceGroupName $resourceGroupName -Name $topicName).Endpoint
    $keys = Get-AzEventGridTopicKey -ResourceGroupName $resourceGroupName -Name $topicName
    
  3. 准备事件。Prepare the event. 在 PowerShell 窗口中复制并运行这些语句。Copy and run the statements in the PowerShell window.

    $eventID = Get-Random 99999
    
    #Date format should be SortableDateTimePattern (ISO 8601)
    $eventDate = Get-Date -Format s
    
    #Construct body using Hashtable
    $htbody = @{
        id= $eventID
        eventType="recordInserted"
        subject="myapp/vehicles/motorcycles"
        eventTime= $eventDate   
        data= @{
            make="Ducati"
            model="Monster"
        }
        dataVersion="1.0"
    }
    
    #Use ConvertTo-Json to convert event body from Hashtable to JSON Object
    #Append square brackets to the converted JSON payload since they are expected in the event's JSON payload syntax
    $body = "["+(ConvertTo-Json $htbody)+"]"
    
  4. 使用 Invoke-WebRequest cmdlet 发送事件。Use the Invoke-WebRequest cmdlet to send the event.

    Invoke-WebRequest -Uri $endpoint -Method POST -Body $body -Headers @{"aeg-sas-key" = $keys.Key1}
    

在事件网格查看器中验证Verify in the Event Grid Viewer

现已触发事件,并且事件网格已将消息发送到订阅时配置的终结点。You've triggered the event, and Event Grid sent the message to the endpoint you configured when subscribing. 导航到事件网格触发器函数并打开日志。Navigate to your Event Grid triggered function and open the logs. 这时应该会在日志中看到该事件的数据有效负载的副本。You should see a copy of the data payload of the event in the logs. 如果不确定,请先打开日志窗口,或点击重新连接,然后再次尝试发送测试事件。If you don't make sure you open the logs window first, or hit reconnect, and then try sending a test event again.

成功的函数触发器日志

清理资源Clean up resources

如果打算继续处理此事件,请不要清除本文中创建的资源。If you plan to continue working with this event, don't clean up the resources created in this article. 否则,请删除本文中创建的资源。Otherwise, delete the resources you created in this article.

  1. 在左侧菜单中选择“资源组”。Select Resource Groups on the left menu. 如果左侧菜单中未显示此选项,请在左侧菜单中选择“所有服务”,然后选择“资源组”。 If you don't see it on the left menu, select All Services on the left menu, and select Resource Groups.

  2. 选择资源组以启动“资源组”页。 Select the resource group to launch the Resource Group page.

  3. 在工具栏中选择“删除资源组”。Select Delete resource group on the toolbar.

  4. 输入资源组的名称以确认删除,然后选择“删除”。 Confirm deletion by entering the name of the resource group, and select Delete.

    资源组

后续步骤Next steps

了解如何创建主题和事件订阅以后,即可进一步学习事件网格的功能:Now that you know how to create topics and event subscriptions, learn more about what Event Grid can help you do: