.net - Azure 服务总线队列。我多次收到同一条消息

标签 .net azure azure-servicebus-queues

我调用了 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/

相关文章:

c# - 有问题的组合框 Windows 窗体

c# - 如何等待 SqlTransaction 提交而不是抛出 SqlException

Azure 辅助角色 VM 规范

azure - 无法使用托管标识从 Azure API 将消息发布到 Azure 服务总线队列

.NET 相当于 Java Servlet 和 Apache Tomcat

.net - 使用 DataDog 收集 OpenTelemetry 跟踪

c# - PostSharp 对速度没有影响

python - Microsoft BotFramework Python 机器人部署

azure - peek 和 receive 之间的区别(Azure 服务总线)

ibm-mq - 是否有办法在 Azure 服务总线队列和 WebSphere 队列之间进行桥接?