教程:使用 Azure 资源管理器模板配置 IoT 中心消息路由Tutorial: Use an Azure Resource Manager template to configure IoT Hub message routing

消息路由能够将遥测数据从 IoT 设备发送到内置的与事件中心兼容的终结点或自定义终结点,例如,Blob 存储、服务总线队列、服务总线主题和事件中心。Message routing enables sending telemetry data from your IoT devices to built-in Event Hub-compatible endpoints or custom endpoints such as blob storage, Service Bus Queues, Service Bus Topics, and Event Hubs. 若要配置自定义消息路由,请创建路由查询来自定义与特定条件匹配的路由。To configure custom message routing, you create routing queries to customize the route that matches a certain condition. 设置完成后,引入的数据将通过 IoT 中心自动路由到终结点。Once set up, the incoming data is automatically routed to the endpoints by the IoT Hub. 如果某个消息不匹配定义的任何路由查询,它将路由到默认终结点。If a message doesn't match any of the defined routing queries, it is routed to the default endpoint.

本教程包括 2 个部分,介绍如何通过 IoT 中心设置和使用这些自定义路由查询。In this 2-part tutorial, you learn how to set up and use these custom routing queries with IoT Hub. 将消息从 IoT 设备路由到多个终结点中的一个,包括 Blob 存储和服务总线队列。You route messages from an IoT device to one of multiple endpoints, including blob storage and a Service Bus queue. 路由到服务总线队列的消息将由逻辑应用拾取,并通过电子邮件发送。Messages to the Service Bus queue are picked up by a Logic App and sent via e-mail. 未定义自定义消息路由的消息将发送到默认终结点,然后由 Azure 流分析拾取,可在 Power BI 中直观查看。Messages that do not have custom message routing defined are sent to the default endpoint, then picked up by Azure Stream Analytics and viewed in a Power BI visualization.

若要完成本教程的第 1 和第 2 部分,请执行以下任务:To complete Parts 1 and 2 of this tutorial, you perform the following tasks:

第 I 部分:创建资源并设置消息路由Part I: Create resources, set up message routing

  • 创建资源 - IoT 中心、存储帐户、服务总线队列和模拟设备。Create the resources -- an IoT hub, a storage account, a Service Bus queue, and a simulated device. 使用 Azure 门户、Azure 资源管理器模板、Azure CLI 或 Azure PowerShell 即可完成此操作。This can be done using the Azure portal, an Azure Resource Manager template, the Azure CLI, or Azure PowerShell.
  • 在 IoT 中心为存储帐户和服务总线队列配置终结点和消息路由。Configure the endpoints and message routes in IoT Hub for the storage account and Service Bus queue.

第 II 部分:将消息发送到中心并查看路由的结果Part II: Send messages to the hub, view routed results

  • 创建一个逻辑应用,该应用将在消息添加到服务总线队列时触发,并发送电子邮件。Create a Logic App that is triggered and sends e-mail when a message is added to the Service Bus queue.
  • 下载并运行应用,该应用模拟 IoT 设备将消息发送到中心,以获得不同的路由选择。Download and run an app that simulates an IoT Device sending messages to the hub for the different routing options.
  • 为发送至默认终结点的数据创建 Power BI 可视化。Create a Power BI visualization for data sent to the default endpoint.
  • 查看结果...View the results ...
  • ...在服务总线队列和电子邮件中。...in the Service Bus queue and e-mails.
  • ...在存储帐户中。...in the storage account.
  • ...在 Power BI 可视化中。...in the Power BI visualization.

先决条件Prerequisites

  • 对于本教程的第 1 部分:For Part 1 of this tutorial:

    • 必须拥有 Azure 订阅。You must have an Azure subscription. 如果没有 Azure 订阅,可以在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.
  • 对于本教程的第 2 部分:For Part 2 of this tutorial:

    • 必须事先完成本教程的第 1 部分,并保留一些可用的资源。You must have completed Part 1 of this tutorial, and have the resources still available.
    • 安装 Visual StudioInstall Visual Studio.
    • 有权访问用于分析默认终结点的流分析的 Power BI 帐户。Have access to a Power BI account to analyze the default endpoint's stream analytics. 免费试用 Power BI。)(Try Power BI for free.)
    • 提供一个用于发送通知电子邮件的 Office 365 帐户。Have an Office 365 account for sending notification e-mails.

创建基础资源Create base resources

在配置消息路由之前,需创建 IoT 中心、存储帐户和服务总线队列。Before you can configure the message routing, you need to create an IoT hub, a storage account, and a Service Bus queue. 可以参阅适用于本教程第 1 部分的四篇文章中的一篇来创建这些资源:Azure门户、Azure 资源管理器模板、Azure CLI 或 Azure PowerShell。These resources can be created using one of the four articles that are available for Part 1 of this tutorial: the Azure portal, an Azure Resource Manager template, the Azure CLI, or Azure PowerShell.

为所有资源使用相同的资源组和位置。Use the same resource group and location for all of the resources. 在本教程结束后,可以通过删除资源组一次性删除所有资源。Then at the end, you can remove all of the resources in one step by deleting the resource group.

下面是将在以下部分中执行的步骤摘要:Below is a summary of the steps to be performed in the following sections:

  1. 创建资源组Create a resource group.

  2. 在 S1 层级中创建 IoT 中心。Create an IoT hub in the S1 tier. 将使用者组添加到 IoT 中心。Add a consumer group to your IoT hub. 检索数据时,Azure 流分析使用使用者组。The consumer group is used by the Azure Stream Analytics when retrieving data.

    备注

    必须使用付费层中的 IoT 中心来完成本教程。You must use an Iot hub in a paid tier to complete this tutorial. 免费层只允许设置一个终结点,但本教程需要多个终结点。The free tier only allows you to set up one endpoint, and this tutorial requires multiple endpoints.

  3. 使用 Standard_LRS 副本创建标准 V1 存储帐户。Create a standard V1 storage account with Standard_LRS replication.

  4. 创建服务总线命名空间和队列。Create a Service Bus namespace and queue.

  5. 为发送消息到中心的模拟设备创建设备标识。Create a device identity for the simulated device that sends messages to your hub. 保存测试阶段的密钥。Save the key for the testing phase. (如果创建资源管理器模板,则会在部署模板后执行此操作。)(If creating a Resource Manager template, this is done after deploying the template.)

消息路由Message routing

根据模拟设备附加到消息的属性将消息路由到不同资源。You are going to route messages to different resources based on properties attached to the message by the simulated device. 未自定义路由的消息将发送到默认终结点(消息/事件)。Messages that are not custom routed are sent to the default endpoint (messages/events). 在下一教程中,我们会将消息发送到 IoT 中心,看其如何路由到不同的目标。In the next tutorial, you send messages to the IoT Hub and see them routed to the different destinations.

ValueValue 结果Result
级别=“storage”level="storage" 写入到 Azure 存储。Write to Azure Storage.
级别=“critical”level="critical" 写入服务总线队列。Write to a Service Bus queue. 逻辑应用从队列检索消息并使用 Office 365 通过电子邮件发送该消息。A Logic App retrieves the message from the queue and uses Office 365 to e-mail the message.
默认值default 使用 Power BI 显示此数据。Display this data using Power BI.

第一步是设置终结点,以便将数据路由到其中。The first step is to set up the endpoint to which the data will be routed. 第二步是设置使用该终结点的消息路由。The second step is to set up the message route that uses that endpoint. 设置路由后,即可在门户中查看终结点和消息路由。After setting up the routing, you can view the endpoints and message routes in the portal.

下载模板和参数文件Download the template and parameters file

在本教程的第二部分,我们将下载并运行一个 Visual Studio 应用程序,以将消息发送到 IoT 中心。For the second part of this tutorial, you download and run a Visual Studio application to send messages to the IoT Hub. 该下载内容的某个文件夹中包含 Azure 资源管理器模板和参数文件,以及 Azure CLI 和 PowerShell 脚本。There is a folder in that download that contains the Azure Resource Manager template and parameters file, as well as the Azure CLI and PowerShell scripts.

现在请继续下载 Azure IoT C# 示例Go ahead and download the Azure IoT C# Samples now. 解压缩 master.zip 文件。Unzip the master.zip file. 资源管理器模板和参数文件位于 /iot-hub/Tutorials/Routing/SimulatedDevice/resources/ 中,其文件名分别为 template_iothub.jsontemplate_iothub_parameters.jsonThe Resource Manager template and the parameters file are in /iot-hub/Tutorials/Routing/SimulatedDevice/resources/ as template_iothub.json and template_iothub_parameters.json.

创建资源Create your resources

我们将使用 Azure 资源管理器 (RM) 模板来创建所有资源。You're going to use an Azure Resource Manager (RM) template to create all of your resources. 每次可以运行几行 Azure CLI 和 PowerShell 脚本。The Azure CLI and PowerShell scripts can be run a few lines at a time. RM 模板是通过一个步骤部署的。An RM template is deployed in one step. 本文通过单独的部分来介绍每种方法。This article shows you the sections separately to help you understand each one. 然后,介绍如何部署模板,以及创建虚拟设备用于测试。Then it will show you how to deploy the template, and create the virtual device for testing. 部署模板后,可以在门户中查看消息路由配置。After the template is deployed, you can view the message routing configuration in the portal.

有几个资源名称必须全局唯一,例如 IoT 中心名称和存储帐户名称。There are several resource names that must be globally unique, such as the IoT Hub name and the storage account name. 为了简化资源的命名,将在设置的这些资源名称后面追加一个基于当前日期/时间随机生成的字母数字值。To make naming the resources easier, those resource names are set up to append a random alphanumeric value generated from the current date/time.

查看模板时,将会看到为这些资源设置的变量的位置。这些变量采用传入的参数,并将 randomValue 连接到该参数。If you look at the template, you'll see where variables are set up for these resources that take the parameter passed in and concatenate randomValue to the parameter.

以下部分将解释所用的参数。The following section explains the parameters used.

parametersParameters

其中的大部分参数都具有默认值。Most of these parameters have default values. _in 结尾的参数将与 randomValue 相连接,使参数名称全局唯一。The ones ending with _in are concatenated with randomValue to make them globally unique.

randomValue:此值是基于部署模板时的日期/时间生成的。randomValue: This value is generated from the current date/time when you deploy the template. 此字段不包含在参数文件中,因为它是在模板本身中生成的。This field is not in the parameters file, as it is generated in the template itself.

subscriptionId:此字段用于标识要在其中部署模板的订阅。subscriptionId: This field is set for you to the subscription into which you are deploying the template. 此字段不包含在参数文件中,因为它是由系统设置的。This field is not in the parameters file since it is set for you.

IoTHubName_in:此字段是基本 IoT 中心名称,与 randomValue 相连接,使名称全局唯一。IoTHubName_in: This field is the base IoT Hub name, which is concatenated with the randomValue to be globally unique.

location:此字段是要部署到的 Azure 区域。location: This field is the Azure region into which you are deploying.

consumer_group:此字段是为通过路由终结点传入的消息设置的使用者组。consumer_group: This field is the consumer group set for messages coming through the routing endpoint. 它用于筛选 Azure 流分析中的结果。It is used to filter results in Azure Stream Analytics. 例如,如果我们想要获取整个流中的所有内容,或者数据通过设置为 Contoso 的 consumer_group 传入,则我们可将 Azure 流分析流(和 Power BI 报表)设置为仅显示这些条目。For example, there is the whole stream where you get everything, or if you have data coming through with consumer_group set to Contoso, then you can set up an Azure Stream Analytics stream (and Power BI report) to show only those entries. 本教程的第 2 部分将使用此字段。This field is used in part 2 of this tutorial.

sku_name:此字段是 IoT 中心的规模。sku_name: This field is the scaling for the IoT Hub. 此值必须为 S1 或更高;免费层不适用于本教程,因为它不允许多个终结点。This value must be S1 or above; a free tier does not work for this tutorial because it does not allow multiple endpoints.

sku_units:此字段类似于 sku_name,表示可以使用的 IoT 中心单位数。sku_units: This field goes with the sku_name, and is the number of IoT Hub units that can be used.

d2c_partitions:此字段表示用于事件流的分区数。d2c_partitions: This field is the number of partitions used for the event stream.

storageAccountName_in:此字段是要创建的存储帐户的名称。storageAccountName_in: This field is the name of the storage account to be created. 消息将路由到存储帐户中的容器。Messages are routed to a container in the storage account. 此字段与 randomValue 相连接,使名称全局唯一。This field is concatenated with the randomValue to make it globally unique.

storageContainerName:此字段是路由到存储帐户的消息的存储容器。storageContainerName: This field is the name of the container in which the messages routed to the storage account are stored.

storage_endpoint:此字段是消息路由使用的存储帐户终结点的名称。storage_endpoint: This field is the name for the storage account endpoint used by the message routing.

service_bus_namespace_in:此字段是要创建的服务总线命名空间的名称。service_bus_namespace_in: This field is the name of the Service Bus namespace to be created. 此值与 randomValue 相连接,使名称全局唯一。This value is concatenated with the randomValue to make it globally unique.

service_bus_queue_in:此字段是用于路由消息的服务总线队列的名称。service_bus_queue_in: This field is the name of the Service Bus queue used for routing messages. 此值与 randomValue 相连接,使名称全局唯一。This value is concatenated with the randomValue to make it globally unique.

AuthRules_sb_queue:此字段是服务总线队列的授权规则,用于检索队列的连接字符串。AuthRules_sb_queue: This field is the authorization rules for the service bus queue, used to retrieve the connection string for the queue.

变量Variables

这些值将在模板中使用,往往派生自参数。These values are used in the template, and are mostly derived from parameters.

queueAuthorizationRuleResourceId:此字段是服务总线队列的授权规则的 ResourceId。queueAuthorizationRuleResourceId: This field is the ResourceId for the authorization rule for the Service Bus queue. 而 ResourceId 用于检索队列的连接字符串。ResourceId is in turn used to retrieve the connection string for the queue.

iotHubName:此字段是连接 randomValue 后的 IoT 中心名称。iotHubName: This field is the name of the IoT Hub after having randomValue concatenated.

storageAccountName:此字段是连接 randomValue 后的存储帐户名称。storageAccountName: This field is the name of the storage account after having randomValue concatenated.

service_bus_namespace:此字段是连接 randomValue 后的命名空间。service_bus_namespace: This field is the namespace after having randomValue concatenated.

service_bus_queue:此字段是连接 randomValue 后的服务总线队列名称。service_bus_queue: This field is the Service Bus queue name after having randomValue concatenated.

sbVersion:要使用的服务总线 API 版本。sbVersion: THe version of the Service Bus API to use. 在本例中为“2017-04-01”。In this case, it is "2017-04-01".

资源:存储帐户和容器Resources: Storage account and container

创建的第一个资源是存储帐户,以及消息要路由到的容器。The first resource created is the storage account, along with the container to which messages are routed. 容器是存储帐户下的资源。The container is a resource under the storage account. 容器具有存储帐户的 dependsOn 子句,因此,必须先创建存储帐户,再创建容器。It has a dependsOn clause for the storage account, requiring the storage account be created before the container.

下面是此节的外观:Here's what this section looks like:

{
    "type": "Microsoft.Storage/storageAccounts",
    "name": "[variables('storageAccountName')]",
    "apiVersion": "2018-07-01",
    "location": "[parameters('location')]",
    "sku": {
        "name": "Standard_LRS",
        "tier": "Standard"
    },
    "kind": "Storage",
    "properties": {},
    "resources": [
        {
        "type": "blobServices/containers",
        "apiVersion": "2018-07-01",
        "name": "[concat('default/', parameters('storageContainerName'))]",
        "properties": {
            "publicAccess": "None"
            } ,
        "dependsOn": [
            "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
            ]
        }
    ]
}

资源:服务总线命名空间和队列Resources: Service Bus namespace and queue

创建的第二个资源是服务总线命名空间,以及消息要路由到的服务总线队列。The second resource created is the Service Bus namespace, along with the Service Bus queue to which messages are routed. SKU 设置为“标准”。The SKU is set to standard. 从变量中检索 API 版本。The API version is retrieved from the variables. 此资源设置为在部署此节时激活服务总线命名空间 (status:Active)。It is also set to activate the Service Bus namespace when it deploys this section (status:Active).

{
    "type": "Microsoft.ServiceBus/namespaces",
    "comments": "The Sku should be 'Standard' for this tutorial.",
    "sku": {
        "name": "Standard",
        "tier": "Standard"
    },
    "name": "[variables('service_bus_namespace')]",
    "apiVersion": "[variables('sbVersion')]",
    "location": "[parameters('location')]",
    "properties": {
        "provisioningState": "Succeeded",
        "metricId": "[concat('a4295411-5eff-4f81-b77e-276ab1ccda12:', variables('service_bus_namespace'))]",
        "serviceBusEndpoint": "[concat('https://', variables('service_bus_namespace'),'.servicebus.windows.net:443/')]",
        "status": "Active"
    },
    "dependsOn": []
}

此节创建服务总线队列。This section creates the Service Bus queue. 此脚本部分包含 dependsOn 子句,用于确保先创建命名空间,再创建队列。This part of the script has a dependsOn clause that ensures the namespace is created before the queue.

{
    "type": "Microsoft.ServiceBus/namespaces/queues",
    "name": "[concat(variables('service_bus_namespace'), '/', variables('service_bus_queue'))]",
    "apiVersion": "[variables('sbVersion')]",
    "location": "[parameters('location')]",
    "scale": null,
    "properties": {},
    "dependsOn": [
        "[resourceId('Microsoft.ServiceBus/namespaces', variables('service_bus_namespace'))]"
    ]
}

资源:IoT 中心和消息路由Resources: Iot Hub and message routing

创建存储帐户和服务总线队列后,可以创建要将消息路由到的 IoT 中心。Now that the storage account and Service Bus queue have been created, you create the IoT Hub that routes messages to them. RM 模板使用 dependsOn 子句,因此,它不会在创建服务总线资源和存储帐户之前尝试创建中心。The RM template uses dependsOn clauses so it doesn't try to create the hub before the Service Bus resources and the storage account have been created.

下面是 IoT 中心节的第一个部分。Here's the first part of the IoT Hub section. 此模板部分设置依赖项,以属性开头。This part of the template sets up the dependencies and starts with the properties.

{
    "apiVersion": "2018-04-01",
    "type": "Microsoft.Devices/IotHubs",
    "name": "[variables('IoTHubName')]",
    "location": "[parameters('location')]",
    "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]",
        "[resourceId('Microsoft.ServiceBus/namespaces', variables('service_bus_namespace'))]",
        "[resourceId('Microsoft.ServiceBus/namespaces/queues', variables('service_bus_namespace'), variables('service_bus_queue'))]"
    ],
    "properties": {
        "eventHubEndpoints": {}
            "events": {
                "retentionTimeInDays": 1,
                "partitionCount": "[parameters('d2c_partitions')]"
                }
            },

下一节是 Iot 中心的消息路由配置节。The next section is the section for the message routing configuration for the Iot Hub. 首先是终结点节。First is the section for the endpoints. 此模板部分设置服务总线队列和存储帐户的路由终结点,包括连接字符串。This part of the template sets up the routing endpoints for the Service Bus queue and the storage account, including the connection strings.

若要创建队列的连接字符串,需要使用内联检索的 queueAuthorizationRulesResourcedId。To create the connection string for the queue, you need the queueAuthorizationRulesResourcedId, which is retrieved inline. 若要创建存储帐户的连接字符串,需要检索主存储密钥,然后在连接字符串的格式中使用该密钥。To create the connection string for the storage account, you retrieve the primary storage key and then use it in the format for the connection string.

也需要在终结点配置中将 Blob 格式设置为 AVROJSONThe endpoint configuration is also where you set the blob format to AVRO or JSON.

备注

可以将数据以 Apache Avro 格式(默认)或 JSON 格式(预览版)写入 Blob 存储。The data can be written to blob storage in either the Apache Avro format, which is the default, or JSON (preview).

JSON 格式编码的功能现处于预览版状态,IoT 中心可在任意区域使用(美国东部、美国西部和欧洲西部除外)。The capability to encode JSON format is in preview in all regions in which IoT Hub is available, except East US, West US and West Europe. 编码格式只能在配置 Blob 存储终结点时设置。The encoding format can be only set at the time the blob storage endpoint is configured. 不能更改已设置的终结点的格式。The format cannot be changed for an endpoint that has already been set up. 使用 JSON 编码时,必须在消息系统属性中将 contentType 设置为 JSON,将 contentEncoding 设置为 UTF-8。When using JSON encoding, you must set the contentType to JSON and the contentEncoding to UTF-8 in the message system properties.

若要更详细地了解如何使用 Blob 存储终结点,请参阅有关如何路由到存储的指南For more detailed information about using a blob storage endpoint, please see guidance on routing to storage.

"routing": {
   "endpoints": {
       "serviceBusQueues": [
       {
           "connectionString": "[Concat('Endpoint=sb://',variables('service_bus_namespace'),'.servicebus.windows.net/;SharedAccessKeyName=',parameters('AuthRules_sb_queue'),';SharedAccessKey=',listkeys(variables('queueAuthorizationRuleResourceId'),variables('sbVersion')).primaryKey,';EntityPath=',variables('service_bus_queue'))]",
           "name": "[parameters('service_bus_queue_endpoint')]",
           "subscriptionId": "[parameters('subscriptionId')]", 
           "resourceGroup": "[resourceGroup().Name]"
       }
       ],
       "serviceBusTopics": [],
       "eventHubs": [],
       "storageContainers": [
           {
               "connectionString": 
               "[Concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageAccountName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]",
               "containerName": "[parameters('storageContainerName')]",
               "fileNameFormat": "{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}",
               "batchFrequencyInSeconds": 100,
               "maxChunkSizeInBytes": 104857600,
               "encoding": "avro",
               "name": "[parameters('storage_endpoint')]",
               "subscriptionId": "[parameters('subscriptionId')]",
               "resourceGroup": "[resourceGroup().Name]"
           }
       ]
   },

下一节是用于将消息路由到终结点。This next section is for the message routes to the endpoints. 每个终结点存在一项设置,因此,服务总线队列和存储帐户容器各有一项设置。There is one set up for each endpoint, so there is one for the Service Bus queue and one for the storage account container.

请记住,路由到存储的消息的查询条件是 level="storage",路由到服务总线队列的消息的查询条件是 level="critical"Remember that the query condition for the messages being routed to storage is level="storage", and the query condition for the messages being routed to the Service Bus queue is level="critical".

"routes": [
    {
        "name": "contosoStorageRoute",
        "source": "DeviceMessages",
        "condition": "level=\"storage\"",
        "endpointNames": [
            "[parameters('storage_endpoint')]"
            ],
        "isEnabled": true
    },
    {
        "name": "contosoSBQueueRoute",
        "source": "DeviceMessages",
        "condition": "level=\"critical\"",
        "endpointNames": [
            "[parameters('service_bus_queue_endpoint')]"
            ],
        "isEnabled": true
    }
],

此 JSON 演示了 IoT 中心节的余下内容,其中包含默认信息和中心的 SKU。This json shows the rest of the IoT Hub section, which contains default information and the SKU for the hub.

            "fallbackRoute": {
                "name": "$fallback",
                "source": "DeviceMessages",
                "condition": "true",
                "endpointNames": [
                    "events"
                ],
                "isEnabled": true
            }
        },
        "storageEndpoints": {
            "$default": {
                "sasTtlAsIso8601": "PT1H",
                "connectionString": "",
                "containerName": ""
            }
        },
        "messagingEndpoints": {
            "fileNotifications": {
                "lockDurationAsIso8601": "PT1M",
                "ttlAsIso8601": "PT1H",
                "maxDeliveryCount": 10
            }
        },
        "enableFileUploadNotifications": false,
        "cloudToDevice": {
            "maxDeliveryCount": 10,
            "defaultTtlAsIso8601": "PT1H",
            "feedback": {
                "lockDurationAsIso8601": "PT1M",
                "ttlAsIso8601": "PT1H",
                "maxDeliveryCount": 10
            }
        }
    },
    "sku": {
        "name": "[parameters('sku_name')]",
        "capacity": "[parameters('sku_units')]"
    }
}

资源:服务总线队列授权规则Resources: Service Bus queue authorization rules

服务总线队列授权规则用于检索服务总线队列的连接字符串。The Service Bus queue authorization rule is used to retrieve the connection string for the Service Bus queue. 它使用 dependsOn 子句来确保先创建服务总线命名空间和服务总线队列,然后再创建授权规则。It uses a dependsOn clause to ensure it is not created before the Service Bus namespace and the Service Bus queue.

{
    "type": "Microsoft.ServiceBus/namespaces/queues/authorizationRules",
    "name": "[concat(variables('service_bus_namespace'), '/', variables('service_bus_queue'), '/', parameters('AuthRules_sb_queue'))]",
    "apiVersion": "[variables('sbVersion')]",
    "location": "[parameters('location')]",
    "scale": null,
    "properties": {
        "rights": [
            "Send"
        ]
    },
    "dependsOn": [
        "[resourceId('Microsoft.ServiceBus/namespaces', variables('service_bus_namespace'))]",
        "[resourceId('Microsoft.ServiceBus/namespaces/queues', variables('service_bus_namespace'), variables('service_bus_queue'))]"
    ]
},

资源:使用者组Resources: Consumer group

在此节中,创建 Azure 流分析在本教程第二部分使用的 IoT 中心数据的使用者组。In this section, you create a Consumer Group for the IoT Hub data to be used by the Azure Stream Analytics in the second part of this tutorial.

{
    "type": "Microsoft.Devices/IotHubs/eventHubEndpoints/ConsumerGroups",
    "name": "[concat(variables('iotHubName'), '/events/',parameters('consumer_group'))]",
    "apiVersion": "2018-04-01",
    "dependsOn": [
        "[concat('Microsoft.Devices/IotHubs/', variables('iotHubName'))]"
    ]
}

资源:OutputsResources: Outputs

若要将值发回到部署脚本以供显示,请使用 output 节。If you want to send a value back to the deployment script to be displayed, you use an output section. 此模板部分返回服务总线队列的连接字符串。This part of the template returns the connection string for the Service Bus queue. 不一定要返回值;包含值的目的是通过示例演示如何向调用方脚本返回结果。Returning a value isn't required, it's included as an example of how to return results to the calling script.

"outputs": {
    "sbq_connectionString": {
      "type": "string",
      "value": "[Concat('Endpoint=sb://',variables('service_bus_namespace'),'.servicebus.windows.net/;SharedAccessKeyName=',parameters('AuthRules_sb_queue'),';SharedAccessKey=',listkeys(variables('queueAuthorizationRuleResourceId'),variables('sbVersion')).primaryKey,';EntityPath=',variables('service_bus_queue'))]"
    }
  }

创建模拟设备Create simulated device

接下来,创建设备标识并保存其密钥供之后使用。Next, create a device identity and save its key for later use. 此设备标识由模拟应用程序用来发送消息到 IoT 中心。This device identity is used by the simulation application to send messages to the IoT hub. 此功能在 PowerShell 中不可用,在使用 Azure 资源管理器模板时也不可用。This capability is not available in PowerShell or when using an Azure Resource Manager template. 以下步骤介绍如何使用 Azure 门户创建模拟设备。The following steps tell you how to create the simulated device using the Azure portal.

  1. 打开 Azure 门户并登录到 Azure 帐户。Open the Azure portal and log into your Azure account.

  2. 选择“资源组”,然后选择你的资源组 。Select Resource groups and then choose your resource group. 本教程使用 ContosoResources 。This tutorial uses ContosoResources.

  3. 在资源列表中,选择 IoT 中心。In the list of resources, select your IoT hub. 本教程使用 ContosoTestHub 。This tutorial uses ContosoTestHub. 从中心窗格选择“IoT 设备” 。Select IoT Devices from the Hub pane.

  4. 选择“+ 添加” 。Select + Add. 在添加设备窗格中,填写设备 ID。On the Add Device pane, fill in the device ID. 本教程使用 Contoso-Test-Device 。This tutorial uses Contoso-Test-Device. 将密钥留空,勾选“自动生成密钥” 。Leave the keys empty, and check Auto Generate Keys. 确保已启用“将设备连接到 IoT 中心” 。Make sure Connect device to IoT hub is enabled. 选择“保存” 。Select Save.

    “添加设备”屏幕

  5. 创建设备后,即可选择它来查看生成的密钥。Now that it's been created, select the device to see the generated keys. 选择主密钥上的“复制”图标,将其保存在某个位置(如记事本)供本教程的测试阶段使用。Select the Copy icon on the Primary key and save it somewhere such as Notepad for the testing phase of this tutorial.

    设备详细信息(包括密钥)

在门户中查看消息路由View message routing in the portal

设置终结点和消息路由以后,即可在门户中查看其配置。Now that your endpoints and message routes are set up, you can view their configuration in the portal. 登录 Azure 门户,转到“资源组”。 Sign in to the Azure portal and go to Resource Groups. 接下来选择你的资源组,然后选择中心(在本教程中,中心名称以 ContosoTestHub 开头)。Next, select your resource group, then select your hub (the hub name starts with ContosoTestHub in this tutorial). 此时会看到“IoT 中心”窗格。You see the IoT Hub pane.

IoT 中心属性平面

在适用于 IoT 中心的选项中,选择“消息路由”。 In the options for the IoT Hub, select Message Routing. 此时会显示已成功设置的路由。The routes you have set up successfully are displayed.

已设置的路由

在“消息路由”屏幕上 选择“自定义终结点” ,查看为路由定义的终结点。On the Message routing screen, select Custom Endpoints to see the endpoints you have defined for the routes.

为路由设置的终结点

后续步骤Next steps

设置所有资源并配置消息路由后,请继续学习下一篇教程,了解如何处理和显示有关路由的消息的信息。Now that you have all of the resources set up and the message routes are configured, advance to the next tutorial to learn how to process and display the information about the routed messages.