开发者

Azure Storage Connection Check

开发者 https://www.devze.com 2023-03-11 23:14 出处:网络
I have a console application which uploads jobs to the workers running in the cloud. The application connects to Azure Storage and uploads some files to blobs and put some messages to queues. Currentl

I have a console application which uploads jobs to the workers running in the cloud. The application connects to Azure Storage and uploads some files to blobs and put some messages to queues. Currently, I am using the development storage. I actually want to know at which state my client application connects to the storage. Can I create a queueClient even though I do not have any connection at all? At which step it actually tries to send some network packages? I actually 开发者_开发知识库need some kind of a mechanism in order to check the existence of the connection and the validity of the storage account.


The client doesn't send any messages until you call a command on the storage - e.g. until you try to get or put a property of a blob, container, or queue - e.g. in the sample code below (from http://msdn.microsoft.com/en-us/library/gg651129.aspx) then messages are sent in 3 specific places:

            // Variables for the cloud storage objects.
            CloudStorageAccount cloudStorageAccount;
            CloudBlobClient blobClient;
            CloudBlobContainer blobContainer;
            BlobContainerPermissions containerPermissions;
            CloudBlob blob;

            // Use the local storage account.
            cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;

            // If you want to use Windows Azure cloud storage account, use the following
            // code (after uncommenting) instead of the code above.
            // cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=your_storage_account_name;AccountKey=your_storage_account_key");

            // Create the blob client, which provides
            // authenticated access to the Blob service.
            blobClient = cloudStorageAccount.CreateCloudBlobClient();

            // Get the container reference.
            blobContainer = blobClient.GetContainerReference("mycontainer");

            // Create the container if it does not exist.
            // MESSAGE SENT
            blobContainer.CreateIfNotExist();

            // Set permissions on the container.
            containerPermissions = new BlobContainerPermissions();
            // This sample sets the container to have public blobs. Your application
            // needs may be different. See the documentation for BlobContainerPermissions
            // for more information about blob container permissions.
            containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;

            // MESSAGE SENT
            blobContainer.SetPermissions(containerPermissions);

            // Get a reference to the blob.
            blob = blobContainer.GetBlobReference("myfile.txt");

            // Upload a file from the local system to the blob.
            Console.WriteLine("Starting file upload");

            // MESSAGE SENT
            blob.UploadFile(@"c:\myfiles\myfile.txt");  // File from local storage.

            Console.WriteLine("File upload complete to blob " + blob.Uri);

One way to check whether you have connectivity is to use some of the simple functions like CreateIfNotExist() or GetPermissions() on a known container - these give you a simple quick method to check connectivity. You can also use the BlobRequestOptions to specify a timeout to make sure your app doesn't hang (http://msdn.microsoft.com/en-us/library/ee772886.aspx)

Be careful not to check connectivity too frequently - every 10000 successful checks will cost you $0.01


Adding to what Stuart has written above, what you can do is try and list 1 queue from your storage account using CloudQueueClient.ListQueuesSegmented Method (http://msdn.microsoft.com/en-us/library/ff361716.aspx). We're really not interested in the result as such. What we're more interested in is if we get a storage client exception or not which you will get if the credentials are not correct. Even if you don't have a queue in your storage account, as long as you have passed correct credentials you will not get an error.

Somehow I don't feel creating an object would be the right thing to test storage account credentials. In the past we've seen situations where a storage account was made read only and even if you pass valid credentials and try to see if the credentials are correct by creating an object, you would get an error.

Hope this helps.


Here's how we check if the connection is ready:

    public async Task<bool> IsReady()
    {
        var options = new BlobRequestOptions { ServerTimeout = TimeSpan.FromSeconds(2), MaximumExecutionTime = TimeSpan.FromSeconds(2) };
        var container = GetStorageClient().GetContainerReference("status");
        var blobRef = container.GetBlockBlobReference("health-check");
        try
        {
            await blobRef.DownloadTextAsync(null, options, null);
        }
        catch (StorageException e)
        {
            if (e.RequestInformation.HttpStatusCode != 404)
                return false;

            try
            {
                await container.CreateIfNotExistsAsync(options, null);
                await blobRef.UploadTextAsync("health check", AccessCondition.GenerateEmptyCondition(), options, null);
            }
            catch (Exception)
            {
                return false;
            }
        }

        return true;
    }
  • GetStorageClient() is a custom method, replace with your own

What it does:

  • We try to read a test file because reading is much cheaper than write operations
  • If the exception is "file not found" let's try to create the file
  • If exception is other than 404 we can stop here, trying to write should make no sense

Note: When using "cool" storage using an "other operation" would be cheaper. See https://azure.microsoft.com/en-us/pricing/details/storage/blobs/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号