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

使用 IoT 中心消息路由将设备到云消息发送到不同的终结点Use IoT Hub message routing to send device-to-cloud messages to different endpoints

备注

本文中提到的某些功能 (如云到设备的消息传送、设备孪生和设备管理) 仅在 IoT 中心的标准层中提供。Some of the features mentioned in this article, like cloud-to-device messaging, device twins, and device management, are only available in the standard tier of IoT Hub. 有关基本和标准 IoT 中心层的详细信息,请参阅如何选择合适的 IoT 中心层For more information about the basic and standard IoT Hub tiers, see How to choose the right IoT Hub tier.

消息路由使你能够以自动、可缩放以及可靠的方式将消息从设备发送到云服务。Message routing enables you to send messages from your devices to cloud services in an automated, scalable, and reliable manner. 消息路由可用于:Message routing can be used for:

  • 发送设备遥测消息以及事件(即设备生命周期事件和设备孪生更改事件)到内置终结点和自定义终结点。Sending device telemetry messages as well as events namely, device lifecycle events, and device twin change events to the built-in-endpoint and custom endpoints. 了解有关路由终结点Learn about routing endpoints.

  • 在将数据路由到各个终结点之前对数据进行筛选,筛选方法是通过应用丰富的查询。Filtering data before routing it to various endpoints by applying rich queries. 消息路由允许你查询消息属性和消息正文以及设备孪生标记和设备孪生属性。Message routing allows you to query on the message properties and message body as well as device twin tags and device twin properties. 深入了解如何使用消息路由中的查询Learn more about using queries in message routing.

IoT 中心需要这些服务终结点的写入权限,以便使用消息路由。IoT Hub needs write access to these service endpoints for message routing to work. 如果通过 Azure 门户配置终结点,则为你添加必要权限。If you configure your endpoints through the Azure portal, the necessary permissions are added for you. 请确保将服务配置为支持预期吞吐量。Make sure you configure your services to support the expected throughput. 例如,如果将事件中心用作自定义终结点,则必须配置该事件中心的吞吐量单位,使其能够处理计划通过 IoT 中心消息路由发送的事件的入口。For example, if you are using Event Hubs as a custom endpoint, you must configure the throughput units for that event hub so it can handle the ingress of events you plan to send via IoT Hub message routing. 同样,使用服务总线队列作为终结点时,必须配置最大大小,以确保队列可以包含所有数据引入,直到使用者出口。Similarly, when using a Service Bus Queue as an endpoint, you must configure the maximum size to ensure the queue can hold all the data ingressed, until it is egressed by consumers. 在首次配置 IoT 解决方案时,可能需要监视附加终结点,并针对实际负载进行任意的必要调整。When you first configure your IoT solution, you may need to monitor your additional endpoints and make any necessary adjustments for the actual load.

IoT 中心为所有“设备到云”消息传递定义通用格式,以实现跨协议的互操作性。The IoT Hub defines a common format for all device-to-cloud messaging for interoperability across protocols. 如果某条消息与多个路由匹配,而这些路由指向同一终结点,则 IoT 中心仅向该终结点传递一次消息。If a message matches multiple routes that point to the same endpoint, IoT Hub delivers message to that endpoint only once. 因此无需在服务总线队列或主题中配置重复数据删除。Therefore, you don't need to configure deduplication on your Service Bus queue or topic. 在分区队列中,分区相关性可保障消息排序。In partitioned queues, partition affinity guarantees message ordering. 使用本教程了解如何配置消息路由Use this tutorial to learn how to configure message routing.

路由终结点Routing endpoints

IoT 中心有一个默认的内置终结点(消息/事件),此终结点与事件中心兼容。An IoT hub has a default built-in-endpoint (messages/events) that is compatible with Event Hubs. 可以通过将订阅中的其他服务链接到中心来创建要将消息路由到的自定义终结点You can create custom endpoints to route messages to by linking other services in your subscription to the IoT Hub.

每条消息都路由到其路由查询匹配的所有终结点。Each message is routed to all endpoints whose routing queries it matches. 换句话说,消息可以路由到多个终结点。In other words, a message can be routed to multiple endpoints.

IoT 中心目前支持将以下服务作为自定义终结点:IoT Hub currently supports the following services as custom endpoints:

内置终结点Built-in endpoint

可以使用标准事件中心集成和 SDK 接收来自内置终结点(消息/事件)的设备到云的消息。You can use standard Event Hubs integration and SDKs to receive device-to-cloud messages from the built-in endpoint (messages/events). 在创建一个路由后,数据将停止流向内置终结点,除非创建了到该终结点的路由。Once a Route is created, data stops flowing to the built-in-endpoint unless a Route is created to that endpoint.

Azure Blob 存储Azure Blob Storage

IoT 中心支持将数据以 Apache Avro 格式和 JSON 格式写入 Azure Blob 存储。IoT Hub supports writing data to Azure Blob Storage in the Apache Avro format as well as in JSON format. 编码 JSON 格式的功能通常可在 IoT 中心可用的所有区域中使用。The capability to encode JSON format is generally available in all regions in which IoT Hub is available. 默认值为 AVRO。The default is AVRO. 只有在配置 Blob 存储终结点时才能设置编码格式。The encoding format can be only set when the blob storage endpoint is configured. 不能编辑现有终结点的格式。The format cannot be edited for an existing endpoint. 使用 JSON 编码时,必须将 contentType 设置为application/JSON ,并将 contentEncoding 设置为消息系统属性中的utf-8When using JSON encoding, you must set the contentType to application/json and contentEncoding to UTF-8 in the message system properties. 这两个值都是不区分大小写的。Both of these values are case-insensitive. 如果未设置内容编码,则 IoT 中心将以基本64编码格式编写消息。If the content encoding is not set, then IoT Hub will write the messages in base 64 encoded format. 可以使用 IoT 中心的创建或更新 REST API(具体说来就是 RoutingStorageContainerProperties、Azure 门户、Azure CLIAzure Powershell)选择编码格式。You can select the encoding format using the IoT Hub Create or Update REST API, specifically the RoutingStorageContainerProperties, the Azure portal, Azure CLI, or the Azure Powershell. 下图说明如何在 Azure 门户中选择编码格式。The following diagram shows how to select the encoding format in the Azure portal.

Blob 存储终结点编码

IoT 中心还支持将消息路由到Azure Data Lake Storage (ADLS) Gen2 帐户,这是基于 Blob 存储构建的已启用分层命名空间的存储帐户。IoT Hub also supports routing messages to Azure Data Lake Storage (ADLS) Gen2 accounts, which are hierarchical namespace-enabled storage accounts built on top of Blob storage. 此功能处于公共预览阶段,适用于美国西部 2 和美国中西部的新 ADLS Gen2 帐户。This capability is in public preview and available for new ADLS Gen2 accounts in West US 2 and West Central US. 注册以预览此。Please sign up to preview this. 我们将很快在所有云区域推出此功能。We will roll out this capability to all cloud regions soon.

IoT 中心将在消息达到特定大小或在经过一定的事件后,对消息进行批处理并将数据写入 Blob。IoT Hub batches messages and writes data to a blob whenever the batch reaches a certain size or a certain amount of time has elapsed. IoT 中心默认为以下文件命名约定:IoT Hub defaults to the following file naming convention:

{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}

你可以使用任何文件命名约定,但必须使用所有列出的令牌。You may use any file naming convention, however you must use all listed tokens. 如果没有要写入的数据,IoT 中心会写入到一个空 blob。IoT Hub will write to an empty blob if there is no data to write.

在路由到 blob 存储时,请列出 blob,再循环访问它们,以确保读取所有容器而不进行任何分区假设。When routing to blob storage, we recommend enlisting the blobs and then iterating over them, to ensure all containers are read without making any assumptions of partition. Microsoft 发起的故障转移或 IoT 中心手动故障转移期间,分区范围可能发生变化。The partition range could potentially change during a Microsoft-initiated failover or IoT Hub manual failover. 可以使用 List Blobs API 来枚举 Blob 的列表。You can use the List Blobs API to enumerate the list of blobs. 请将以下示例作为指南来查看。Please see the following sample as guidance.

     public void ListBlobsInContainer(string containerName, string iothub)
     {
         var storageAccount = CloudStorageAccount.Parse(this.blobConnectionString);
         var cloudBlobContainer = storageAccount.CreateCloudBlobClient().GetContainerReference(containerName);
         if (cloudBlobContainer.Exists())
         {
             var results = cloudBlobContainer.ListBlobs(prefix: $"{iothub}/");
             foreach (IListBlobItem item in results)
             {
                 Console.WriteLine(item.Uri);
             }
         }
     }

服务总线队列和服务总线主题Service Bus Queues and Service Bus Topics

用作 IoT 中心终结点的服务总线队列和主题不得启用会话重复检测选项。Service Bus queues and topics used as IoT Hub endpoints must not have Sessions or Duplicate Detection enabled. 如果启用了其中任一选项,该终结点会在 Azure 门户中显示为无法访问If either of those options are enabled, the endpoint appears as Unreachable in the Azure portal.

事件中心Event Hubs

除了与事件中心兼容的内置终结点外,还可以将数据路由到事件中心类型的自定义终结点。Apart from the built-in-Event Hubs compatible endpoint, you can also route data to custom endpoints of type Event Hubs.

读取已路由的数据Reading data that has been routed

可以按照此教程配置一个路由。You can configure a route by following this tutorial.

使用以下教程了解如何从终结点读取消息。Use the following tutorials to learn how to read message from an endpoint.

回退路由Fallback route

回退路由将所有不满足任何现有路由上的查询条件的消息发送到与事件中心兼容的内置事件中心(消息/事件)。The fallback route sends all the messages that don't satisfy query conditions on any of the existing routes to the built-in-Event Hubs (messages/events), that is compatible with Event Hubs. 如果已启用消息路由,则可以启用此回退路由功能。If message routing is turned on, you can enable the fallback route capability. 在创建一个路由后,数据将停止流向内置终结点,除非创建了到该终结点的路由。Once a route is created, data stops flowing to the built-in-endpoint, unless a route is created to that endpoint. 如果没有到内置终结点的路由并且已启用回退路由,则仅与路由上的任何查询条件不匹配的消息将被发送到内置终结点。If there are no routes to the built-in-endpoint and a fallback route is enabled, only messages that don't match any query conditions on routes will be sent to the built-in-endpoint. 此外,如果已删除现有路由,必须启用回退路由才能接收内置终结点处的所有数据。Also, if all existing routes are deleted, fallback route must be enabled to receive all data at the built-in-endpoint.

可以在 "Azure 门户 > 消息路由" 边栏选项卡中启用/禁用回退路由。You can enable/disable the fallback route in the Azure portal->Message Routing blade. 还可以将 Azure 资源管理器用于 FallbackRouteProperties 来为回退路由使用自定义终结点。You can also use Azure Resource Manager for FallbackRouteProperties to use a custom endpoint for fallback route.

非遥测事件Non-telemetry events

除了设备遥测以外,消息路由还启用发送设备克隆更改事件、设备生命周期事件和数字克隆更改事件(公共预览版)。In addition to device telemetry, message routing also enables sending device twin change events, device lifecycle events, and digital twin change events (in public preview). 例如,如果使用数据源创建一个设置为到设备孪生更改事件的路由,IoT 中心会将消息发送到包含设备孪生更改的终结点。For example, if a route is created with data source set to device twin change events, IoT Hub sends messages to the endpoint that contain the change in the device twin. 同样,如果创建了一个路由,并将数据源设置为设备生命周期事件,则 IoT 中心将发送一条消息,指示设备是否已删除或创建。Similarly, if a route is created with data source set to device lifecycle events, IoT Hub sends a message indicating whether the device was deleted or created. 最后,作为IoT 即插即用公共预览版的一部分,开发人员可以创建路由,并将数据源设置为数字克隆更改事件,而 IoT 中心会在每次设置或更改数字克隆属性时发送消息,即数字输出将被替换,或者基础设备克隆发生更改事件时。Finally, as part of the IoT Plug and Play public preview, a developer can create routes with data source set to digital twin change events and IoT Hub sends messages whenever a digital twin property is set or changed, a digital twin is replaced, or when a change event happens for the underlying device twin.

IoT 中心还集成了 Azure 事件网格来发布设备事件以支持基于这些事件的工作流的实时集成和自动化。IoT Hub also integrates with Azure Event Grid to publish device events to support real-time integrations and automation of workflows based on these events. 请参阅消息路由和事件网格之间的主要区别来了解哪种更适合你的方案。See key differences between message routing and Event Grid to learn which works best for your scenario.

测试路由Testing routes

在创建新路由或编辑现有路由时,应通过示例消息来测试路由查询。When you create a new route or edit an existing route, you should test the route query with a sample message. 可以测试单个路由或一次测试所有路由,并且在测试期间,不会有消息被路由到终结点。You can test individual routes or test all routes at once and no messages are routed to the endpoints during the test. Azure 门户、Azure 资源管理器、Azure PowerShell 和 Azure CLI 可用于测试。Azure portal, Azure Resource Manager, Azure PowerShell, and Azure CLI can be used for testing. 结果有助于确定示例消息是否与查询匹配、消息是否与查询不匹配,或测试无法运行,因为示例消息或查询语法不正确。Outcomes help identify whether the sample message matched the query, message did not match the query, or test couldn't run because the sample message or query syntax are incorrect. 若要了解详细信息,请参阅测试路由测试所有路由To learn more, see Test Route and Test all routes.

延迟Latency

使用内置终结点路由设备到云遥测消息时,在创建第一个路由后,端到端延迟略微增大。When you route device-to-cloud telemetry messages using built-in endpoints, there is a slight increase in the end-to-end latency after the creation of the first route.

大多数情况下,延迟的平均增加时间小于500毫秒。In most cases, the average increase in latency is less than 500 ms. 可以使用路由:消息/事件的消息延迟或 d2c.endpoints.latency.builtIn.events IoT 中心指标来监视延迟。You can monitor the latency using Routing: message latency for messages/events or d2c.endpoints.latency.builtIn.events IoT Hub metric. 在创建第一个路由后创建或删除任何路由不会影响端到端延迟。Creating or deleting any route after the first one does not impact the end-to-end latency.

监视和故障排除Monitoring and troubleshooting

IoT 中心提供了多个与路由和终结点相关的指标,使你能够大致了解你的中心的运行状况和已发送的消息数。IoT Hub provides several metrics related to routing and endpoints to give you an overview of the health of your hub and messages sent. 你可以组合来自多项指标的信息来确定问题的根本原因。You can combine information from multiple metrics to identify root cause for issues. 例如,使用指标路由:已删除的遥测消息数或 d2c.telemetry.egress.dropped 来确定当消息与任何路由上的查询不匹配并且已禁用回退路由时已删除的消息数。For example, use metric Routing: telemetry messages dropped or d2c.telemetry.egress.dropped to identify the number of messages that were dropped when they didn't match queries on any of the routes and fallback route was disabled. IoT 中心指标列出了默认为 IoT 中心启用的所有指标。IoT Hub metrics lists all metrics that are enabled by default for your IoT Hub.

可以使用 REST API Get Endpoint Health 获取终结点的运行状况状态You can use the REST API Get Endpoint Health to get health status of the endpoints. 当终结点运行状况为故障或不正常时,建议使用与路由消息延迟相关的 IoT 中心指标来标识并调试错误。We recommend using the IoT Hub metrics related to routing message latency to identify and debug errors when endpoint health is dead or unhealthy. 例如,对于终结点类型“事件中心”,可以监视 d2c.endpoints.latency.eventHubsFor example, for endpoint type Event Hubs, you can monitor d2c.endpoints.latency.eventHubs. 当 IoT 中心建立了最终一致的运行状况状态以后,系统会将不正常终结点的状态更新为正常。The status of an unhealthy endpoint will be updated to healthy when IoT Hub has established an eventually consistent state of health.

通过使用 Azure Monitor 诊断设置中的路由诊断日志,可以跟踪发生在路由查询和终结点运行状况的评估期间、由 IoT 中心所察觉到的错误,例如某个终结点已失效。Using the routes diagnostic logs in Azure Monitor diagnostic settings, you can track errors that occur during evaluation of a routing query and endpoint health as perceived by IoT Hub, for example when an endpoint is dead. 可以将这些诊断日志发送到 Azure Monitor 日志、事件中心或 Azure 存储进行自定义处理。These diagnostic logs can be sent to Azure Monitor logs, Event Hubs, or Azure Storage for custom processing.

后续步骤Next steps