ServiceBus 重试策略不适用于 QueueClient

ServiceBus Retry policy not working with QueueClient

我想限制 Azure ServiceBus 队列接收器中的重试次数。

使用 MaxRetryCount:3

的控制台应用程序发送消息
private static async Task MainAsync()
    {
        string connectionString = ConfigurationManager.AppSettings["ServiceBusConnection"];
        QueueClient queueClient = QueueClient.CreateFromConnectionString(connectionString, QueueName);
        queueClient.RetryPolicy = new RetryExponential(
                minBackoff: TimeSpan.FromSeconds(0),
                maxBackoff: TimeSpan.FromSeconds(30),
                maxRetryCount: 3);

        string tradeData = File.ReadAllText("TradeSchemaDemo.json");
        var message = new BrokeredMessage(tradeData);
        await queueClient.SendAsync(message);
        await queueClient.CloseAsync();
    }

另外一边我有Azure接收消息的功能,

public static void run([ServiceBusTrigger("TestQueue", AccessRights.Manage, Connection = "servicebusconnection")]string myqueueitem, TraceWriter log)
    {
        retry++;
        System.Console.WriteLine($"Retry attempt {retry}");
        throw new System.Exception("Human error");
        log.Info($"c# servicebus queue trigger function processed message: {myqueueitem}");
    }

不过,我的函数调用了 10 次。为什么??

在这种情况下,RetryPolicy 定义了发送操作的重试次数,而不是在接收端。

接收方重试次数由队列 属性 Max Delivery Count 定义。您可以使用 Service Bus Explorer 之类的工具在队列级别设置它,或者在创建队列时以编程方式设置它:

var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
var queue = new QueueDescription(queueName);
queue.MaxDeliveryCount = 3;
if (!namespaceManager.QueueExists(queueName))
    namespaceManager.CreateQueue(queue);

以防万一,有人想看代码

private static async Task MainAsync()
    {
        string connectionString = ConfigurationManager.AppSettings["ServiceBusConnection"];
        var nm = NamespaceManager.CreateFromConnectionString(connectionString);
        var queue = new QueueDescription(QueueName);
        queue.MaxDeliveryCount = 3;
        if (!nm.QueueExists(QueueName))
            await nm.CreateQueueAsync(queue);

        QueueClient queueClient = QueueClient.CreateFromConnectionString(connectionString, QueueName);
        string tradeData = File.ReadAllText("TradeSchemaDemo.json");
        var message = new BrokeredMessage(tradeData);
        await queueClient.SendAsync(message);
        await queueClient.CloseAsync();
    }