我可以使用重复检测来取消计划的 Azure 服务总线消息吗?

Can I use duplicate detection to cancel a scheduled Azure service bus message?

我正在尝试想出为 Azure 服务总线队列或主题安排消息的最佳方式,同时让选项保持打开状态以立即发送消息而不是计划的消息。如果我尝试在第一条消息的预定时间或之后发送替换消息,我想确保我可以防止创建重复消息。

如果您打开重复检测并且两条消息具有相同的 MessageId,那么在第一条消息的预定入队时间之前发送第二条消息是否会有效地取消预定消息?此外,假设如果计划的消息首先成功排队,第二条消息将被忽略是否安全?

If you turn on duplicate detection and both messages have the same MessageId, does sending the second message prior to the scheduled enqueueing time of the first effectively cancel the scheduled message?

我用下面的示例代码进行测试,发现第二条消息会被忽略。

var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

for (int i = 0; i < 2; i++)
{
    if (i == 0)
    {
        client.SendAsync(new BrokeredMessage("testmes1") { MessageId = "test1", ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(60) }).Wait();
    }
    else
    {
        client.SendAsync(new BrokeredMessage("testmes2") { MessageId = "test1" }).Wait();
    }

} 

从队列中接收消息:

client.OnMessage(message =>
{
    Console.WriteLine(String.Format("Message body: {0}", message.GetBody<String>()));
    Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
});

输出:

如果您想取消已安排的消息,您可以尝试在已安排的消息变为 active.

之前致电 CancelScheduledMessageAsync() method
client.CancelScheduledMessageAsync(sequenceNumber).Wait();