您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用 Azure 门户和事件网格将自定义事件路由到 Web 终结点Quickstart: Route custom events to web endpoint with the Azure portal and Event Grid

Azure 事件网格是针对云的事件处理服务。Azure Event Grid is an eventing service for the cloud. 在本文中,将使用 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. 通常,你会将事件发送到处理事件数据并执行操作的终结点。Typically, you send events to an endpoint that processes the event data and takes actions. 但是,为了简化本文,你将事件发送到收集并显示消息的 Web 应用。However, to simplify this article, you send the events to a web app that collects and displays the messages.

完成后即可看到事件数据已发送到 Web 应用。When you're finished, you see that the event data has been sent to the web app.

查看结果

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

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

启用事件网格资源提供程序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 an existing resource group or select Create new, and enter a name for the resource group.

    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.

    “事件网格主题”主页

创建消息终结点Create a message endpoint

在为自定义主题创建订阅之前,请先创建事件消息的终结点。Before you create a subscription for the custom topic, create an endpoint for the event message. 通常情况下,终结点基于事件数据执行操作。Typically, the endpoint takes actions based on the event data. 为了简化此快速入门,将部署用于显示事件消息的预建的 Web 应用To simplify this quickstart, you deploy a pre-built web app that displays the event messages. 所部署的解决方案包括应用服务计划、应用服务 Web 应用和 GitHub 中的源代码。The deployed solution includes an App Service plan, an App Service web app, and source code from GitHub.

  1. 在项目页中,选择“部署到 Azure”以将解决方案部署到订阅。In the article page, select Deploy to Azure to deploy the solution to your subscription. 在 Azure 门户中,为参数提供值。In the Azure portal, provide values for the parameters.

  2. 部署可能需要几分钟才能完成。The deployment may take a few minutes to complete. 部署成功后,请查看 Web 应用以确保它正在运行。After the deployment has succeeded, view your web app to make sure it's running. 在 Web 浏览器中导航到 https://<your-site-name>.azurewebsites.netIn a web browser, navigate to: https://<your-site-name>.azurewebsites.net

  3. 查看站点,但是尚未有事件发布到它。You see the site but no events have been posted to it yet.

    查看新站点

订阅自定义主题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. 对于“终结点类型”,请选择“Web Hook”。Select Web Hook for the Endpoint type.

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

      提供事件订阅值

    4. 对于 Webhook 终结点,请提供你的 Web 应用的 URL,并将 api/updates 添加到主页 URL。For the web hook endpoint, provide the URL of your web app and add api/updates to the home page URL. 选择“确认所选内容”。Select Confirm Selection.

      提供终结点 URL

    5. 返回“创建事件订阅”页,选择“创建”。Back on the Create Event Subscription page, select Create.

  3. 再次查看 Web 应用,并注意现已向该应用发送了订阅验证事件。View your web app again, and notice that a subscription validation event has been sent to it. 选择眼睛图标以展开事件数据。Select the eye icon to expand the event data. 事件网格发送验证事件,以便终结点可以验证它是否想要接收事件数据。Event Grid sends the validation event so the endpoint can verify that it wants to receive event data. Web 应用包含用于验证订阅的代码。The web app includes code to validate the subscription.

    查看订阅事件

向主题发送事件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. 在 Azure 门户中选择“Cloud Shell”。In the Azure portal, select Cloud Shell. 在 Cloud Shell 窗口的左上角选择“Bash”。Select Bash in the top-left corner of the Cloud Shell window.

    Cloud Shell - Bash

  2. 运行以下命令以获取主题的终结点:复制并粘贴该命令后,更新主题名称资源组名称,然后运行该命令。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)
    
  3. 运行以下命令以获取自定义主题的密钥:复制并粘贴该命令后,更新主题名称资源组名称,然后运行该命令。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)
    
  4. 复制以下包含事件定义的语句,然后按 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"} ]'
    
  5. 运行以下 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. 在 Azure 门户中选择“Cloud Shell”。In the Azure portal, select Cloud Shell. 在 Cloud Shell 窗口的左上角选择“PowerShell”。Select PowerShell in the top-left corner of the Cloud Shell window. 参阅“Azure CLI”部分的示例 Cloud Shell 窗口图像。See the sample Cloud Shell window image in the Azure CLI section.

  2. 运行以下命令以获取主题的终结点:复制并粘贴该命令后,更新主题名称资源组名称,然后运行该命令。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 = (Get-AzEventGridTopic -ResourceGroupName <resource group name> -Name <topic name>).Endpoint
    
  3. 运行以下命令以获取自定义主题的密钥:复制并粘贴该命令后,更新主题名称资源组名称,然后运行该命令。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.

    $keys = Get-AzEventGridTopicKey -ResourceGroupName gridResourceGroup -Name <topic name>
    
  4. 准备事件。Prepare the event. 在 Cloud Shell 窗口中复制并运行这些语句。Copy and run the statements in the Cloud Shell 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)+"]"
    
  5. 使用 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. 查看 Web 应用以查看刚刚发送的事件。View your web app to see the event you just sent.

{
  "id": "974",
  "eventType": "recordInserted",
  "subject": "myapp/vehicles/motorcycles",
  "eventTime": "2019-03-28T01:11:59+00:00",
  "data": {
    "make": "Ducati",
    "model": "Monster"
  },
  "dataVersion": "1.0",
  "metadataVersion": "1",
  "topic": "/subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/myegridrg/providers/Microsoft.EventGrid/topics/myegridtopic"
}

清理资源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.

    资源组

    图中显示的另一个资源组是 Cloud Shell 窗口创建并使用的。The other resource group you see in the image was created and used by the Cloud Shell window. 如果你以后不打算使用 Cloud Shell 窗口,请删除该资源组。Delete it if you don't plan to use the Cloud Shell window later.

后续步骤Next steps

了解如何创建自定义主题和事件订阅后,请详细了解事件网格的功能:Now that you know how to create custom topics and event subscriptions, learn more about what Event Grid can help you do: