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

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

Azure 事件网格是针对云的事件处理服务。Azure Event Grid is an eventing service for the cloud. 在本文中,将使用 Azure CLI 创建一个自定义主题,然后订阅该自定义主题,再触发可查看结果的事件。In this article, you use the Azure CLI 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 订阅,可以在开始前创建一个免费帐户If you don't have an Azure subscription, create a free account before you begin.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 通过 Cloud Shell 可以将 bashPowerShell 与 Azure 服务配合使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. 可以使用 Azure Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要启动 Azure Cloud Shell,请执行以下操作:To launch Azure Cloud Shell:

选项Option 示例/链接Example/Link
选择代码块右上角的“试用”。 Select Try It in the upper-right corner of a code block. 选择“试用” 不会自动将代码复制到 Cloud Shell。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的“试用”示例
转到 https://shell.azure.com 或选择“启动 Cloud Shell” 按钮可在浏览器中打开 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window
选择 Azure 门户右上方菜单栏中的“Cloud Shell” 按钮。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 门户中的“Cloud Shell”按钮

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:To run the code in this article in Azure Cloud Shell:

  1. 打开 Cloud Shell。Open Cloud Shell.
  2. 选择代码块上的“复制”按钮 以复制代码。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上使用 Ctrl+Shift+V 将代码粘贴到 Cloud Shell 会话中,或在 macOS 上使用 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. Enter 运行此代码。Press Enter to run the code.

如果选择在本地安装并使用 CLI,本文需要运行最新版的 Azure CLI(2.0.24 或更高版本)。If you choose to install and use the CLI locally, this article requires that you are running the latest version of Azure CLI (2.0.24 or later). 要查找版本,请运行 az --versionTo find the version, run az --version. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

如果不使用 Cloud Shell,则必须先使用 az login 登录。If you aren't using Cloud Shell, you must first sign in using az login.

创建资源组Create a resource group

事件网格主题是 Azure 资源,必须放置在 Azure 资源组中。Event Grid topics are Azure resources, and must be placed in an Azure resource group. 该资源组是在其中部署和管理 Azure 资源的逻辑集合。The resource group is a logical collection into which Azure resources are deployed and managed.

使用 az group create 命令创建资源组。Create a resource group with the az group create command.

以下示例在“westus2” 位置创建名为“gridResourceGroup” 的资源组。The following example creates a resource group named gridResourceGroup in the westus2 location.

az group create --name gridResourceGroup --location westus2

启用事件网格资源提供程序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. 运行以下命令,注册提供程序:Run the following command to register the provider:

az provider register --namespace Microsoft.EventGrid

完成注册可能需要一些时间。It may take a moment for the registration to finish. 若要检查状态,请运行:To check the status, run:

az provider show --namespace Microsoft.EventGrid --query "registrationState"

registrationStateRegistered 后,即可继续。When registrationState 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. 以下示例在资源组中创建自定义主题。The following example creates the custom topic in your resource group. 用主题的唯一名称替换 <your-topic-name>Replace <your-topic-name> with a unique name for your topic. 自定义主题名称必须唯一,因为它是 DNS 条目的一部分。The custom topic name must be unique because it's part of the DNS entry. 此外,它必须介于 3 到 50 个字符之间,并且只包含值 a-z、A-Z、0-9 和“-”Additionally, it must be between 3-50 characters and contain only values a-z, A-Z, 0-9, and "-"

topicname=<your-topic-name>

az eventgrid topic create --name $topicname -l westus2 -g gridResourceGroup

创建消息终结点Create a message endpoint

在订阅自定义主题之前,让我们创建事件消息的终结点。Before subscribing to the custom topic, let's create the 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.

<your-site-name> 替换为 Web 应用的唯一名称。Replace <your-site-name> with a unique name for your web app. Web 应用名称必须唯一,因为它是 DNS 条目的一部分。The web app name must be unique because it's part of the DNS entry.

sitename=<your-site-name>

az group deployment create \
  --resource-group gridResourceGroup \
  --template-uri "https://raw.githubusercontent.com/Azure-Samples/azure-event-grid-viewer/master/azuredeploy.json" \
  --parameters siteName=$sitename hostingPlanName=viewerhost

部署可能需要几分钟才能完成。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

应会看到站点上当前未显示任何消息。You should see the site with no messages currently displayed.

订阅自定义主题Subscribe to a custom topic

订阅事件网格主题,以告知事件网格要跟踪哪些事件,以及要将这些事件发送到何处。You subscribe to an event grid topic to tell Event Grid which events you want to track and where to send those events. 以下示例将订阅所创建的自定义主题,并将 Web 应用中的 URL 作为事件通知的终结点传递。The following example subscribes to the custom topic you created, and passes the URL from your web app as the endpoint for event notification.

Web 应用的终结点必须包括后缀 /api/updates/The endpoint for your web app must include the suffix /api/updates/.

endpoint=https://$sitename.azurewebsites.net/api/updates

az eventgrid event-subscription create \
  --source-resource-id "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.EventGrid/topics/$topicname" 
  --name demoViewerSub 
  --endpoint $endpoint
  

再次查看 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 custom topic

让我们触发一个事件,看看事件网格如何将消息分发到终结点。Let's trigger an event to see how Event Grid distributes the message to your endpoint. 首先,让我们获取自定义主题的 URL 和密钥。First, let's get the URL and key for the custom topic.

endpoint=$(az eventgrid topic show --name $topicname -g gridResourceGroup --query "endpoint" --output tsv)
key=$(az eventgrid topic key list --name $topicname -g gridResourceGroup --query "key1" --output tsv)

为简化本文,将使用要发送到自定义主题的示例事件数据。To simplify this article, you use sample event data to send to the custom topic. 通常情况下,应用程序或 Azure 服务会发送事件数据。Typically, an application or Azure service would send the event data. 以下示例创建示例事件数据:The following example creates sample event data:

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"} ]'

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. 本文使用 CURL 向主题发送事件。In this article, use CURL to send the event to the topic.

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

现已触发事件,并且事件网格已将消息发送到订阅时配置的终结点。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": "1807",
  "eventType": "recordInserted",
  "subject": "myapp/vehicles/motorcycles",
  "eventTime": "2017-08-10T21:03:07+00:00",
  "data": {
    "make": "Ducati",
    "model": "Monster"
  },
  "dataVersion": "1.0",
  "metadataVersion": "1",
  "topic": "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.EventGrid/topics/{topic}"
}]

清理资源Clean up resources

如果打算继续处理此事件或事件查看器应用,请不要清除本文中创建的资源。If you plan to continue working with this event or the event viewer app, don't clean up the resources created in this article. 否则,请使用以下命令删除本文中创建的资源。Otherwise, use the following command to delete the resources you created in this article.

az group delete --name gridResourceGroup

后续步骤Next steps

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