You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Function(dotnet-isolated运行时)中获取IoT Hub使用信息

获取Azure IoT Hub使用信息的API/SDK方案

1. Azure Monitor指标查询(推荐)

可以通过Azure Monitor的API/SDK获取IoT Hub的核心使用数据,包括总消息发送量、时段内消息发送情况等,完全匹配你需要的统计维度。

针对dotnet-isolated的Azure Function,直接引入Azure.Monitor.Query NuGet包即可实现调用,示例代码如下:

using Azure.Monitor.Query;
using Azure.Identity;

var metricsClient = new MetricsQueryClient(new DefaultAzureCredential());
var resourceId = "/subscriptions/{你的订阅ID}/resourceGroups/{资源组名}/providers/Microsoft.Devices/IotHubs/{IoT Hub名称}";

// 查询近7天的总消息发送量和每日消息发送量
var queryResponse = await metricsClient.QueryResourceAsync(
    resourceId,
    metricNames: new[] { "TotalMessagesSent", "MessagesSent" },
    timeRange: TimeSpan.FromDays(7));

foreach (var metric in queryResponse.Value.Metrics)
{
    Console.WriteLine($"指标名称: {metric.Name.LocalizedValue}");
    foreach (var timeSeries in metric.TimeSeries)
    {
        foreach (var dataPoint in timeSeries.Data)
        {
            Console.WriteLine($"时间: {dataPoint.Timestamp}, 数值: {dataPoint.Value}");
        }
    }
}

支持的关键指标包括:

  • TotalMessagesSent:IoT Hub累计接收的消息总量
  • MessagesSent:指定时段内的消息发送量(可按小时/天聚合)

2. Azure Resource Manager IoT Hub API

如果需要获取资源配额、设备连接数等更偏向资源层面的统计,可以使用Azure Resource Manager的IoT Hub SDK。

在dotnet-isolated环境中引入Azure.ResourceManager.IotHub NuGet包,示例代码:

using Azure.ResourceManager;
using Azure.ResourceManager.IotHub;
using Azure.Identity;

var armClient = new ArmClient(new DefaultAzureCredential());
var iotHubResourceId = IotHubResourceResourceId.Parse("/subscriptions/{你的订阅ID}/resourceGroups/{资源组名}/providers/Microsoft.Devices/IotHubs/{IoT Hub名称}");
var iotHubResource = await armClient.GetIotHubResourceResource(iotHubResourceId).GetAsync();

// 获取配额与使用统计
var quotaMetrics = await iotHubResource.Value.GetIotHubQuotaMetricsAsync();
foreach (var metric in quotaMetrics.Value)
{
    Console.WriteLine($"指标: {metric.Name}, 当前使用量: {metric.CurrentValue}, 配额上限: {metric.MaxValue}");
}

权限说明

确保Azure Function的托管标识(或服务主体)拥有Monitoring Reader或IoT Hub Contributor权限,才能成功读取这些统计数据。

内容的提问来源于stack exchange,提问作者ShresthaGanesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:10:09