【问题标题】:Azure storage - Any timing issues with this code?Azure 存储 - 此代码有任何时间问题吗?
【发布时间】:2015-10-19 19:30:45
【问题描述】:

我正在使用 Azure 存储来存储和检索图像。我有这个方法来保存图像(blob):

public void SaveBlob(string containerName, string blobName, byte[] blob)
{
    // Retrieve reference to the blob
    CloudBlockBlob blockBlob = GetContainer(containerName, true).GetBlockBlobReference(blobName);

    using (var stream = new MemoryStream(blob, writable: false))
    {
        blockBlob.UploadFromStream(stream);
    }
}

这是 GetContainer 方法:

    public CloudBlobContainer GetContainer(string containerName, bool createIfNotExist)
    {
        if (string.IsNullOrEmpty(containerName))
            return null;

        // Retrieve a reference to a container. If container doesn't exist, optionally create it.
        CloudBlobContainer container = this._blobClient.GetContainerReference(containerName);
        if (container == null && !createIfNotExist)
            return null;

        // Create the container if it doesn't already exist. It will be private by default.
        container.CreateIfNotExists(BlobContainerPublicAccessType.Off, null, null);

        return container;
    }

这里发生的情况是,当我尝试保存 blob 时,我首先获得了对容器的引用。如果容器不存在,则创建它,然后保存 blob。如果我必须先创建容器然后立即将 blob 保存到其中,我会在这里遇到时间问题吗?我担心的是,我可能会在 Azure 完成创建之前尝试将 blob 保存到容器中。或者这不是问题?

【问题讨论】:

    标签: azure azure-storage


    【解决方案1】:

    查看您的代码,我认为您不会遇到任何时间问题,因为CreateIfNotExists 方法是一种同步方法,并且只会在创建容器时返回。同样使用 Azure Blob 存储(与 Amazon S3 不同),该方法将立即创建容器,或者如果未能创建容器则抛出错误(或者换句话说,Azure 存储是 Strongly Consistent)。

    另外我觉得这段代码是多余的:

    if (container == null && !createIfNotExist)
                return null;
    

    因为container 永远不会等于null,因此这个if 条件永远不会是true

    【讨论】:

    • 你说容器永远不会等于null。如果容器还不存在,它将等于什么?
    • 当你调用GetContainerReference时,它不会进行网络调用来检查容器是否存在。它只是创建CloudBlobContainer 对象的一个​​实例。然后您可以对该对象执行操作,这些操作(如CreateIfNotExists)将进行网络调用。
    • 啊,我明白了。我需要调用 CloudBlobContainer 上的 Exists 方法来查看容器是否存在。
    • 我不建议这样做。如果容器有可能被其他进程删除,我会坚持使用CreateIfNotExists 调用,以便在上传 blob 之前,始终确保容器存在。为避免CreateIfNotExists 的网络调用开销,您可以将这两种方法分开并分别创建 blob 容器(如果容器对所有用户通用,则可能在应用程序启动期间;如果容器特定于特定用户,则可能在用户注册期间)。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多