首页 > 解决方案 > 消息工作成功完成后 Azure 服务总线“提供的锁无效”

问题描述

我有一个带有以下初始化代码的 Azure Web 作业

class Program
{
    static void Main(string[] args)
    {
        IHostBuilder builder = new HostBuilder()
        .ConfigureWebJobs(b =>
        {
            b.AddServiceBus((opt) =>
            {
                opt.ConnectionString = "Connection string";
                opt.MessageHandlerOptions = new MessageHandlerOptions((ex) =>
                {
                    return Task.Run(() =>
                    {
                        // logging the error message
                    });
                })
                {
                    MaxAutoRenewDuration = new TimeSpan(0, 0, 5, 0),
                    MaxConcurrentCalls = 1
                };
            });
        })
        .UseConsoleLifetime();

        IHost host = builder.Build();
        using (host)
        {
            host.Run();
        }
    }
}

服务总线队列配置为具有 5 分钟的锁定持续时间,这是 Azure 允许的最长时间。消息处理可能需要 30 多分钟,并且锁更新机制正常工作。当进程正确结束时,会抛出异常The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue, or was received by a different receiver instance,消息再次返回队列。

标签: c#azure-webjobsservicebus

解决方案


当您调用messsage.Complete()( 或CompleteAsync()) 时,您应该实例化一个MessageHandlerOptions对象,将AutoComplete设置为false,并将其传递到您的消息处理程序注册中。

new MessageHandlerOptions(OnException)
{
    AutoComplete = false,
    MaxConcurrentCalls = MaxConcurrentCalls, // 1
    MaxAutoRenewDuration = MaxAutoRenewDuration // 2 hrs
}

更多细节,你可以参考这篇文章


推荐阅读