间歇性地找不到 Blob,即使它存在

问题描述 投票:0回答:1

我正在读取 Blob 存储中的文本文件内容,如下所示。当请求不并发时,内容读取得很好。但是,当一次发送多个请求时,我得到 Null 作为响应,这意味着即使文件存在, blobClient.ExistsAsync() 也会返回 false 。我的阅读方式或处理并发问题的方法有什么问题吗?

/// <summary>
/// Extracts the Text content from a file in the Blob Storage.
/// </summary>
/// <param name="blobContainerName">The name of the Container in which the file is present.</param>
/// <param name="blobName">The name of the file to be Read.</param>
/// <returns>
/// File is Present - The Content of the Text File; 
/// File is Empty - An Empty String; 
/// File Not Found - null</returns>

public async Task<string> ReadTextFileFromBlob(string blobContainerName, string blobName)
    {
    // Create a BlobServiceClient using account details
    BlobServiceClient blobServiceClient = _blobServiceClient;

    // Get the container client
    BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient(blobContainerName);

    // Get the blob client
    BlobClient blobClient = blobContainerClient.GetBlobClient(blobName);

    // Check if the blob exists
    if (!await blobClient.ExistsAsync())
    {
        // Return null if the blob does not exist
        return null;
    }
    // Download the blob content as a stream
    using (MemoryStream memoryStream = new MemoryStream())
    {
        await blobClient.DownloadToAsync(memoryStream);

        // Check if the content is empty
        if (memoryStream.Length == 0)
        {
            // Return null if the content is empty
            return "";
        }
        // Convert the stream to a string
        string content = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());

        return content;
    }
}

我尝试查看文档但找不到解决方案。我在互联网上搜索但仍然找不到任何东西。我希望它能够同时支持对 blob 存储中同一文本文件的多个读取请求。

c# azure-blob-storage blob
1个回答
0
投票

我希望它能够同时支持对 blob 存储中同一文本文件的多个读取请求。

您可以使用以下代码同时使用多个请求从 Azure Blob 存储读取相同的

text
文件

代码:

using Azure.Storage.Blobs;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

public class BlobStorageService
{
    private readonly BlobServiceClient _blobServiceClient;

    public BlobStorageService(BlobServiceClient blobServiceClient)
    {
        _blobServiceClient = blobServiceClient;
    }
    public async Task<string> ReadTextFileFromBlobAsync(string blobContainerName, string blobName)
    {
        BlobContainerClient blobContainerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
        BlobClient blobClient = blobContainerClient.GetBlobClient(blobName);

        // Check if the blob exists and log the result
        bool blobExists = await blobClient.ExistsAsync();
        Console.WriteLine($"Blob Exists: {blobExists}");

        if (!blobExists)
        {
            // Return null if the blob does not exist
            return null;
        }

        using (MemoryStream memoryStream = new MemoryStream())
        {
            await blobClient.DownloadToAsync(memoryStream);

            if (memoryStream.Length == 0)
            {
                return "";
            }

            memoryStream.Position = 0; 
            using (StreamReader reader = new StreamReader(memoryStream, Encoding.UTF8))
            {
                string content = await reader.ReadToEndAsync();
                return content;
            }
        }
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        var connectionString = "zzzz"; // Replace with your connection string
        var blobServiceClient = new BlobServiceClient(connectionString);
        var blobStorageService = new BlobStorageService(blobServiceClient);

        string blobContainerName = "data"; 
        string blobName = "file1.txt"; 

        var tasks = new Task<string>[5];

        for (int i = 0; i < tasks.Length; i++)
        {
            tasks[i] = blobStorageService.ReadTextFileFromBlobAsync(blobContainerName, blobName);
        }
        var results = await Task.WhenAll(tasks);
        foreach (var result in results)
        {
            if (result == null)
            {
                Console.WriteLine("File not found.");
            }
            else if (result == "")
            {
                Console.WriteLine("File is empty.");
            }
            else
            {
                Console.WriteLine("File content:");
                Console.WriteLine(result);
            }
        }
    }
}

上面的代码检查 blob 是否存在并打印结果。然后,它将 blob 内容下载到

MemoryStream
,以字符串形式读取
MemoryStream
的内容并返回字符串内容。

main
函数中,它使用 Azure 存储帐户的
BlobServiceClient
创建
connection string
的实例,使用
BlobServiceClient
实例创建 BlobStorageService 的实例,并为每个任务调用
ReadTextFileFromBlobAsync
方法。

输出:

Blob Exists: True
Blob Exists: True
Blob Exists: True
Blob Exists: True
Blob Exists: True
File content:
The sun dipped below the horizon, painting the sky in hues of orange and pink as the evening unfolded. The soft rustling of leaves in the gentle breeze created a soothing symphony, blending with the distant hum of city life. A family of ducks glided gracefully across the tranquil lake, their reflections shimmering on the still water. Nearby, the scent of blooming jasmine filled the air, mingling with the earthy aroma of freshly mowed grass. As night began to fall, stars started to twinkle, casting their celestial glow over the serene landscape, inviting a sense of calm and wonder.
File content:
The sun dipped below the horizon, painting the sky in hues of orange and pink as the evening unfolded. The soft rustling of leaves in the gentle breeze created a soothing symphony, blending with the distant hum of city life. A family of ducks glided gracefully across the tranquil lake, their reflections shimmering on the still water. Nearby, the scent of blooming jasmine filled the air, mingling with the earthy aroma of freshly mowed grass. As night began to fall, stars started to twinkle, casting their celestial glow over the serene landscape, inviting a sense of calm and wonder.
File content:
The sun dipped below the horizon, painting the sky in hues of orange and pink as the evening unfolded. The soft rustling of leaves in the gentle breeze created a soothing symphony, blending with the distant hum of city life. A family of ducks glided gracefully across the tranquil lake, their reflections shimmering on the still water. Nearby, the scent of blooming jasmine filled the air, mingling with the earthy aroma of freshly mowed grass. As night began to fall, stars started to twinkle, casting their celestial glow over the serene landscape, inviting a sense of calm and wonder.
File content:
The sun dipped below the horizon, painting the sky in hues of orange and pink as the evening unfolded. The soft rustling of leaves in the gentle breeze created a soothing symphony, blending with the distant hum of city life. A family of ducks glided gracefully across the tranquil lake, their reflections shimmering on the still water. Nearby, the scent of blooming jasmine filled the air, mingling with the earthy aroma of freshly mowed grass. As night began to fall, stars started to twinkle, casting their celestial glow over the serene landscape, inviting a sense of calm and wonder.
File content:
The sun dipped below the horizon, painting the sky in hues of orange and pink as the evening unfolded. The soft rustling of leaves in the gentle breeze created a soothing symphony, blending with the distant hum of city life. A family of ducks glided gracefully across the tranquil lake, their reflections shimmering on the still water. Nearby, the scent of blooming jasmine filled the air, mingling with the earthy aroma of freshly mowed grass. As night began to fall, stars started to twinkle, casting their celestial glow over the serene landscape, inviting a sense of calm and wonder.
© www.soinside.com 2019 - 2024. All rights reserved.