如何使用 azure 服务总线 5.0.0 在 C# azure 函数中手动处理消息完成

147*_*147 11 c# azure azureservicebus azure-functions

我正在编写一个 Azure 函数来获取 Azure 服务总线中的消息。我想手动处理任何异常("autoCompleteMessages": false)无法弄清楚如何将完整或放弃发送回服务队列。

尝试过选项1:

[FunctionName("SBQ_F1_VC")]
public static async Task Run([ServiceBusTrigger("sbqfn1", Connection = "BrnlTest1_SERVICEBUS")]
    ServiceBusReceivedMessage msg, ILogger log)
{
//.....

    if(!Int32.TryParse(msg.ApplicationProperties.GetValueOrDefault("vid").ToString(), out vid))
    {   await using ServiceBusClient client = new ServiceBusClient(Environment.GetEnvironmentVariable("BrnlTest1_SERVICEBUS"));
        ServiceBusReceiver msgRcvr = client.CreateReceiver(Environment.GetEnvironmentVariable("queueName"), new ServiceBusReceiverOptions()); 
        //await msgRcvr.RenewMessageLockAsync(msg);
        await msgRcvr.AbandonMessageAsync(msg);  //vid = 0;
    }

//.....
}
Run Code Online (Sandbox Code Playgroud)

错误选项 1

System.Private.CoreLib: Exception while executing function: SBQ_F1_VC. Azure.Messaging.ServiceBus: 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. (MessageLockLost).
Run Code Online (Sandbox Code Playgroud)

尝试过选项2:

[FunctionName("SBQ_F1_VC")]
        public static async Task Run([ServiceBusTrigger("sbqfn1", Connection = "BrnlTest1_SERVICEBUS")]
         ServiceBusReceivedMessage[] msgs,
         ServiceBusMessageActions msgActions)
        {
        //.....
        await msgActions.DeadLetterMessageAsync(msg);
        
        }
Run Code Online (Sandbox Code Playgroud)

错误选项 2:

Microsoft.Azure.WebJobs.Host: Error indexing method 'SBQ_F1_VC'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'msgActions' to type ServiceBusMessageActions. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 服务总线是 5.0.0 所以我必须使用Azure.Messaging.ServiceBus命名空间
    • 这意味着消息对象是ServiceBusReceivedMessage

什么有效(基于杰西和乔什的回答)

的参数名称ServiceBusMessageActions 必须messageActions
由于某种原因,更改此名称是不被容忍的......

public static async Task Run(
        [ServiceBusTrigger("sbqfn1", Connection = "BrnlTest1_SERVICEBUS")]
        ServiceBusReceivedMessage[] msgs,
        ServiceBusMessageActions messageActions)
        {
Run Code Online (Sandbox Code Playgroud)

小智 9

您需要使用“messageActions”作为参数名称,而不是“msgActions”。