我有一个物联网设备每 5 分钟向 Azure 物联网中心发送消息。我想将每条消息保存在 Azure Blob 存储容器中。在 Azure 门户内,在
Message routing
部分,我创建了一条像这样的新路线。
接下来,我创建了一个像这样的自定义端点:
通过这样做,我能够将消息保存在 blob 存储中。
我想做的是创建一条动态路线。我希望每条发送的消息都保存在此路径中:{iothub}/{deviceId}/{messageParameter}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}
其中 deviceId
是在 Azure IoT 中心注册的设备的名称,customValue
是 IoT 设备发送到 json 消息的属性值Azure 物联网中心。
这是我用来发送消息的代码:
public class Sender : ISender
{
private static DeviceClient _deviceClient;
public void SendDeviceToCloudMessage(string deviceId, string iotHubUri, string deviceKey, string message)
{
_deviceClient = DeviceClient.Create(iotHubUri,
new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Mqtt);
var twin = _deviceClient.GetTwinAsync().ConfigureAwait(false).GetAwaiter().GetResult();
var desiredProperties = twin.Properties.Desired;
var messageObj = JObject.Parse(message);
if (desiredProperties.Contains("TelemetryData"))
{
var telemetryData = (TwinCollection)desiredProperties["TelemetryData"];
telemetryData["Temperature"] = messageObj["Temperature"];
telemetryData["Humidity"] = messageObj["Humidity"];
telemetryData["TimeStamp"] = messageObj["TimeStamp"];
}
else
{
var telemetryData = new TwinCollection();
telemetryData["Temperature"] = messageObj["Temperature"];
telemetryData["Humidity"] = messageObj["Humidity"];
telemetryData["TimeStamp"] = messageObj["TimeStamp"];
desiredProperties["TelemetryData"] = telemetryData;
}
// Update the reported properties with the updated desired properties
var reportedProperties = new TwinCollection();
reportedProperties["TelemetryData"] = desiredProperties["TelemetryData"];
_deviceClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false).GetAwaiter().GetResult();
using var iotMessage = new Message(Encoding.UTF8.GetBytes(message))
{
ContentEncoding = "utf-8",
ContentType = "application/json",
};
// Submit the message to the hub.
_deviceClient.SendEventAsync(iotMessage).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
message
输入是一个像这样的 json 字符串:
{
"Temperature": 20,
"Humidity": 50,
"TimeStamp": "2023-02-26 14:02:59.7715110 +00:00",
"MessageId": "MessageIdentifier"
}
这可能吗,还是我需要手动将消息保存在 Azure Blob 存储容器中?
注意:我的目标是保存设备发送的消息,随后能够读取特定设备发送的与消息中找到的特定参数相关的消息(因此我将 deviceId 放在路径中)已发送(消息参数)
利用 IoT 中心的存储端点功能无法做到这一点。创建存储端点时,您只能使用以下令牌(并且必须全部使用):
要在路径中包含
deviceId
和 customValue
,您必须自己实现该功能。一种选择是编写一个 Azure 函数来将消息存储在正确的路径中。
您可以考虑使用路由查询和多个端点来实现此目的 (https://learn.microsoft.com/azure/iot-hub/iot-hub-devguide-routing-query-syntax)。但是,您似乎需要为每个设备使用一个单独的 blob 存储端点,并且每个集线器最多只能有 10 个自定义端点。
我注意到您建议的路径包括
{deviceId}
和 {partition}
- 设备对分区“粘性”,因此路径段中存在一些冗余。
总的来说,如果您想要对存储值的路径进行这种级别的控制,您最好将消息路由到 Azure 函数,然后在函数中使用一些逻辑将消息保存到所需结构中的 blob 存储.
您想要使用该特定结构将消息存储在 blob 存储中的原因是什么?