使用 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 endpoints:

  • 内置终结点Built-in endpoint
  • Azure 存储Azure Storage
  • 服务总线队列和服务总线主题Service Bus Queues and Service Bus Topics
  • 事件中心Event Hubs

内置终结点作为路由终结点Built-in endpoint as a routing 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 存储作为路由终结点Azure Storage as a routing endpoint

IoT 中心可将消息路由到以下两个存储服务:Azure Blob 存储Azure Data Lake Storage Gen2 (ADLS Gen2) 帐户。There are two storage services IoT Hub can route messages to -- Azure Blob Storage and Azure Data Lake Storage Gen2 (ADLS Gen2) accounts. Azure Data Lake Storage 帐户是在 Blob 存储之上构建的启用分层命名空间的存储帐户。Azure Data Lake Storage accounts are hierarchical namespace-enabled storage accounts built on top of blob storage. 这两个存储服务都使用 blob 作为其存储。Both of these use blobs for their storage.

IoT 中心支持将数据以 Apache Avro 格式和 JSON 格式写入 Azure 存储。IoT Hub supports writing data to Azure Storage in the Apache Avro format as well as in JSON format. 默认值为 AVRO。The default is AVRO. 使用 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 中心将以 base 64 编码格式写入消息。If the content encoding is not set, then IoT Hub will write the messages in base 64 encoded format.

只有在配置 Blob 存储终结点时才能设置编码格式,不能编辑现有终结点的编码格式。The encoding format can be only set when the blob storage endpoint is configured; it can't be edited for an existing endpoint. 若要为现有终结点切换编码格式,则需要删除现有终结点并重新创建具有所需格式的自定义终结点。To switch encoding formats for an existing endpoint, you'll need to delete and re-create the custom endpoint with the format you want. 一个有用的策略可能是创建具有所需编码格式的新自定义终结点,并将并行路由添加到该终结点。One helpful strategy might be to create a new custom endpoint with your desired encoding format and add a parallel route to that endpoint. 通过这种方式,你可以在删除现有终结点之前验证数据。In this way you can verify your data before deleting the existing endpoint.

可以使用 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 image shows how to select the encoding format in the Azure portal.

Blob 存储终结点编码

IoT 中心将在消息达到特定大小或在经过一定的时间后,对消息进行批处理并将数据写入存储。IoT Hub batches messages and writes data to storage 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 或文件。We recommend listing the blobs or files and then iterating over them, to ensure all blobs or files 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 列表,或使用 List ADLS Gen2 API 枚举文件列表。You can use the List Blobs API to enumerate the list of blobs or List ADLS Gen2 API for the list of files. 请将以下示例作为指南来查看。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);
        }
    }
}

若要创建与 Azure Data Lake Gen2 兼容的存储帐户,请创建新的 V2 存储帐户,并在“高级”选项卡的“分层命名空间”字段上选择“启用”,如下图所示:To create an Azure Data Lake Gen2-compatible storage account, create a new V2 storage account and select enabled on the Hierarchical namespace field on the Advanced tab as shown in the following image:

选择 Azure Date Lake Gen2 存储

服务总线队列和服务总线主题作为路由终结点Service Bus Queues and Service Bus Topics as a routing endpoint

用作 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 as a routing endpoint

除了与事件中心兼容的内置终结点外,还可以将数据路由到事件中心类型的自定义终结点。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

除了设备遥测外,消息路由还可以发送设备孪生更改事件、设备生命周期事件和数字孪生更改事件。例如,如果路由是使用设置为“设备孪生更改事件”的数据源创建的,则 IoT 中心会将包含设备孪生更改的消息发送到终结点。In addition to device telemetry, message routing also enables sending device twin change events, device lifecycle events, and digital twin change events 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 中心还集成了 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.

排序保证至少传送一次Ordering guarantees with at least once delivery

IoT 中心消息路由可保证按顺序至少将消息传送到终结点一次。IoT Hub message routing guarantees ordered and at least once delivery of messages to the endpoints. 这意味着可以存在重复的消息,并且可以按照原始消息顺序重新传输一系列消息。This means that there can be duplicate messages and a series of messages can be retransmitted honoring the original message ordering. 例如,如果原始消息顺序是 [1,2,3,4],则可能会收到类似 [1,2,1,2,3,1,2,3,4] 的消息序列。For example, if the original message order is [1,2,3,4], you could receive a message sequence like [1,2,1,2,3,1,2,3,4]. 排序保证指的是,如果收到过消息 [1],则其后总是 [2,3,4]。The ordering guarantee is that if you ever receive message [1], it would always be followed by [2,3,4].

为了处理消息重复项,我们建议在原点(通常是设备或模块)的消息的应用程序属性中标记一个唯一标识符。For handling message duplicates, we recommend stamping a unique identifier in the application properties of the message at the point of origin, which is usually a device or a module. 传送消息的服务可以使用此标识符来处理重复的消息。The service consuming the messages can handle duplicate messages using this identifier.

延迟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 500ms. 可以使用路由:消息/事件的消息延迟或 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. 有关按功能类别细分的所有 IoT 中心指标的列表,请参阅监视数据参考中的指标For a list of all of the IoT Hub metrics broken out by functional category, see Metrics in the Monitoring data reference. 可以使用 IoT 中心资源日志中的“路由”类别,跟踪发生在路由查询和终结点运行状况评估期间的由 IoT 中心察觉到的错误。You can track errors that occur during evaluation of a routing query and endpoint health as perceived by IoT Hub with the routes category in IoT Hub resource logs. 若要详细了解如何使用 IoT 中心的指标和资源日志,请参阅监视 IoT 中心To learn more about using metrics and resource logs with IoT Hub, see Monitor IoT Hub.

可以使用 REST API Get Endpoint Health 获取终结点的运行状况状态You can use the REST API Get Endpoint Health to get health status of the endpoints.

通过路由故障排除指南获取更多详细信息以及对路由故障排除的支持。Use the troubleshooting guide for routing for more details and support for troubleshooting routing.

后续步骤Next steps