Search code examples
azure-storagelazy-loadinglazy-initializationazure-storage-queuesretrypolicy

Azure storage queue - retry mechanism implementation


Im using nuget package "Microsoft.Azure.Storage.Queue" Version="11.1.7" to create Azure storage queue client as below,

AsyncLazy<CloudQueue> qClient = new AsyncLazy<CloudQueue>( async () =>
    {
        var myStorageAccount = CloudStorageAccount.Parse("ConnectionString");
        var myQueue = myStorageAccount .CreateCloudQueueClient()
            .GetQueueReference("QueueName");
        await myQueue.CreateIfNotExistsAsync();
        return myQueue;
    });

Would like to incorporate retry mechanism to overcome any transient fault while posting message to the queue via above 'qClient' instance.

How to incorporate retry mechanism in the above way of creating Lazy queue connection?


Solution

  • You can refer to this official document, and you can use CloudBlobClient.DefaultRequestOptions Property

    I write a code sample, maybe it can inspire you:

                AsyncLazy<CloudQueue> qClient = new AsyncLazy<CloudQueue>(async () =>
                {
                    var myStorageAccount = CloudStorageAccount.Parse("ConnectionString");
                    var myQueue = myStorageAccount.CreateCloudQueueClient();
                    myQueue.DefaultRequestOptions = new QueueRequestOptions
                    {
                        RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(3), 4),
                        // For Read-access geo-redundant storage, use PrimaryThenSecondary.
                        // Otherwise set this to PrimaryOnly.
                        LocationMode = LocationMode.PrimaryThenSecondary,
                        // Maximum execution time based on the business use case.
                        MaximumExecutionTime = TimeSpan.FromSeconds(20)
                    };
                    var queue = myQueue.GetQueueReference("QueueName");
                    await queue.CreateIfNotExistsAsync();
                    return queue;
                });