简体   繁体   中英

Cache the connection to Azure Blob storage

In the article How to use the Windows Azure Blob Storage Service in .NET the following code is used to demonstrate how one might upload a file

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(@"path\myfile"))
{
    blockBlob.UploadFromStream(fileStream);
}

If you had a long running service that was accepting files and storing them in blob storage would you perform all of these steps every time? Or would you maybe have a class that had a reference to blockBlob that was used by multiple requests? How much (if any) of this is it okay to cache and use from multiple requests? (which I guess means threads)

I concur with @knightpfhor, there is nothing to cache. Until you call UploadFromStream, no long-running transactions have been called. Everything is in memory, constructing objects.

This is not like a Sql Connection, where programmers would find clever ways to cache connections because they were expensive to open - this is REST calls, so every data-changing action is an https call and all the preparation prior to it, is simply light-weight object manipulation

Most of those objects have pretty light weight constructors and are not guaranteed to be thread safe (check the MSDN documentation) so I wouldn't be too concerned about caching them. The only one I tend to keep as a static object is the cloud storage account.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM