我正在开发一个控制台应用程序,它从Azure IoT设备接收消息,并使用计时器每两秒接收一次消息。我遇到的问题是,在设备再次收到消息之前,消息在Azure中没有完成,这会导致消息被重新处理。我曾尝试过滤多次传入的相同消息,但无论是重复消息还是新消息,传入的消息都具有相同的消息id。我没有权限控制传入消息的message id字段并使其唯一,但这将解决问题。序列号对于传入的每个消息都是唯一的,无论它是否重复,因此我也不能将其用作过滤器。有没有办法过滤一条消息,看看它是否是没有消息id字段的重复消息?
//Within Program.cs > Main():
_timer = new Timer(Operations, null, 0, _timerInterval); //_timerInterval is set to 2000
//Within Initialize class used to setup device client:
//Fully qualified namespace for DeviceClient:
//Microsoft.Azure.Devices.Client.DeviceClient
string connectionString = "code removed for example";
var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
//Within Operations class:
var message = await deviceClient.ReceiveAsync();
if (message != null && !string.IsNullOrEmpty(message?.MessageId))
{
//Filtering message based on MessageId
if (_memoryCache.Get(message.MessageId) == null)
{
_memoryCache.Set(message.MessageId, message.MessageId, DateTimeOffset.UtcNow.AddMinutes(10));
await deviceClient.CompleteAsync(message);
//Processing message
await ProcessMessage(message);
}
else
{
await deviceClient.RejectAsync(message);
}
}
发布于 2021-11-20 13:25:42
您可以使用Microsoft.Azure.Devices.Client.Message
包来检索设备客户端消息值。
使用消息中的IOT显式唯一标识在接收时检查重复项。
按照以下代码检查重复的值
List<string> FinalResponse = new List<string>();
Microsoft.Azure.Devices.Client.Message Response = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(10));
if (Response == null)
{
await Task.Delay(10).ConfigureAwait(false);
continue;
}
//here you can use the explicit properties like message id or correlation Id
Trace.WriteLine(Response.MessageId.ToString());
await this.deviceClient.CompleteAsync(Response);
var content = Encoding.UTF8.GetString(Response.GetBytes());
FinalResponse.Add(content);
您可以使用上面的一个条件或使用下面的条件
创建List
和将所有从设备获取的值添加到列表中
将条件添加到如果在插入到列表中时出现任何重复,则忽略。
然后将未复制的值发送到Azure。
https://stackoverflow.com/questions/70027968
复制相似问题