我有一个 web api 项目,用户可以在其中上传图像,我将其存储在 Azure blob 中。代码如下:
public class AzureImageHandler : IImageHandler
{
public async Task<string> StoreImage(byte[] image)
{
var storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
var blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
var container = blobClient.GetContainerReference("images");
// Create the container if it doesn't already exist.
container.CreateIfNotExists();
container.SetPermissions(
new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
// Retrieve reference to a blob named "myblob".
var blockBlob = container.GetBlockBlobReference("myblob");
await blockBlob.UploadFromByteArrayAsync(image, 0, image.Length);
return blockBlob.Uri.ToString();
}
}
我使用 Autofac 设置了 DI,想知道是否有任何代码是线程安全的。即我是否可以拥有一个所有请求都用于获取对新 blob 的引用的单例容器,或者我是否需要每次都运行整个方法?我无法确定 CloudStorageAccount/BlobClient/Container 是否线程安全。
谢谢
请您参考如下方法:
来自 CloudBlobContainer 的文档类:
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
我相信您也会在其他类(class)中找到类似的东西。
如果可以的话,我想提出两个建议:
container.CreateIfNotExists();
container.SetPermissions(
new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
针对每个请求执行以下 2 行代码。如果您相当确定 blob 容器将存在于您的存储帐户中,则可以删除这些代码行,因为这两行代码都会进行网络调用并可能降低您的系统速度。如果您的所有用户都在同一个容器中上传文件,您可以在应用程序的启动中移动此代码。
