【问题标题】:Delete files older than X number of days from Azure Blob Storage using Azure function使用 Azure 函数从 Azure Blob 存储中删除超过 X 天的文件
【发布时间】:2019-11-16 03:12:57
【问题描述】:

我想创建一个 Azure 函数,用于在上次修改时间超过 30 天时从 azure blob 存储中删除文件。 任何人都可以帮助或有文档来做到这一点吗?

【问题讨论】:

  • 嗨 Dani,欢迎来到 SO。你有一些反对意见,因为回答问题的人通常喜欢看到你已经投入了一些工作。那么您是否自己进行了一些研究/谷歌搜索,以及您在什么时候被阻止了。您绝对可以使用 Azure Functions 执行此操作。看看Timer TriggersCloudBlobClient
  • 类似情况请看我的回答here

标签: azure azure-functions azure-blob-storage


【解决方案1】:

假设您的存储帐户类型是General Purpose v2 (GPv2)Blob Storage,您实际上不必自己做任何事情。 Azure 存储可以为您做到这一点。

您将使用 Blob Lifecycle Management 并在其中定义一个策略以删除超过 30 天的 blob,Azure 存储将为您处理删除。

您可以在此处了解更多信息:https://docs.microsoft.com/en-us/azure/storage/blobs/storage-lifecycle-management-concepts

【讨论】:

  • 我一辈子都找不到“生命周期管理”的选项。它还在吗?
  • @Murphybro2 它位于“存储帐户”->“Blob 服务”->“生命周期管理”下
  • 我在“存储帐户”->“数据管理”->“生命周期管理”下找到它。
【解决方案2】:

您可以创建一个 Timer Trigger 函数,从 Blob Container 中获取项目列表并删除不符合您上次修改日期条件的文件。

  1. 创建Timer Trigger function
  2. 获取list of blobs using CloudBlobContainer
  3. 将 blob 项目转换为正确的类型和check LastModified property
  4. Delete the blob 不符合条件。

我希望能回答这个问题。

【讨论】:

    【解决方案3】:

    我使用 HTTP 作为触发器,因为您没有指定一个,而且它更容易测试,但是对于 Timer 触发器等逻辑将是相同的。还假设 C#:

    [FunctionName("HttpTriggeredFunction")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        [Blob("sandbox", Connection = "StorageConnectionString")] CloudBlobContainer container,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
    
        // Get a list of all blobs in your container
        BlobResultSegment result = await container.ListBlobsSegmentedAsync(null);
    
        // Iterate each blob
        foreach (IListBlobItem item in result.Results)
        {
            // cast item to CloudBlockBlob to enable access to .Properties
            CloudBlockBlob blob = (CloudBlockBlob)item;
    
            // Calculate when LastModified is compared to today
            TimeSpan? diff = DateTime.Today - blob.Properties.LastModified;
            if (diff?.Days > 30)
            {
                // Delete as necessary
                await blob.DeleteAsync();
            }
        }
    
        return new OkObjectResult(null);
    }
    

    编辑 - 如何下载 JSON 文件并使用 Newtonsoft.Json 反序列化为对象:

    public class MyClass
    {
        public string Name { get; set; }
    }
    
    var json = await blob.DownloadTextAsync();
    var myClass = JsonConvert.DeserializeObject<MyClass>(json);
    

    【讨论】:

    • 这非常有用。知道如何将每个 blob 反序列化为特定的 DTO?
    • @l--''''''------'''''''''''' 不太清楚你的意思?你的 blob 的内容是什么?
    • 这将是一个 json 有效负载,我想将其反序列化为常规 c# 类
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2022-06-10
    • 1970-01-01
    • 2014-07-20
    • 2021-12-12
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多