我调用了 client.Send(brokeredMessage);
一次,但我多次收到该消息。对于句柄队列,我使用此代码
private static void HandleQueue(string queueName, MessageHandler messageHandler)
{
// Create the queue if it does not exist already
string connectionString =
Configuration.GetConnectionString("Microsoft.ServiceBus.ConnectionString",false);
var namespaceManager =
NamespaceManager.CreateFromConnectionString(connectionString);
if (!namespaceManager.QueueExists(queueName))
{
namespaceManager.CreateQueue(queueName);
}
QueueClient client =
QueueClient.CreateFromConnectionString(connectionString, queueName);
while (true)
{
BrokeredMessage message = client.Receive();
if (message != null)
{
try
{
messageHandler(message);
// Remove message from queue
message.Complete();
}
catch (Exception)
{
// Indicate a problem, unlock message in queue
message.Abandon();
}
}
}
}
问题是,如果执行 messageHandler(message);
需要很长时间,BrokeredMessage message = client.Receive();
会被多次调用并返回相同的消息。我该如何修复它?
最佳答案
当您正在处理消息时,该消息正在被解锁。设置消息锁定超时的正确位置是 QueueDescription
http://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.queuedescription.lockduration.aspx
此处允许的最长时间为 5 分钟,因此如果您需要处理更长时间的消息,则可以对消息调用 RenewLock
以继续使其对其他使用者不可见。您是对的,在完成处理之前调用 Complete
是不可取的,因为如果您处理崩溃,那么您将不会再次收到消息。
上面提到的 BrokeredMessage.ScheduledEnqueueTimeUtc
属性用于“延迟”消息从队列显示给消费者的时间。假设您在第 1 天发送消息并将计划时间设置为第 2 天,那么直到第 2 天,Recieve
调用才会返回该消息。
关于.net - Azure 服务总线队列。我多次收到同一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17787186/