文档中心 > 设置桶的生命周期
设置桶的生命周期

最近更新时间:2022-07-25

UOS支持设置生命周期(Lifecycle)规则,自动删除过期的文件和碎片,或将到期的文件转储为低频或归档存储类型,从而节省存储费用。

每条规则包含:

  • 规则ID。用于标识一条规则,同一桶内规则ID不能重复。

  • 策略。有以下两种设置方式。同一桶内仅支持一种设置方式。

    • 按前缀匹配。此种方式允许创建多条规则,前缀不能重复。

    • 配置到整个桶。此种方式只能创建一条规则。

  • 过期时间。有两种指定方式:

    • 指定一个过期天数N,文件会在其最近更新时间点的N天后过期。

    • 指定一个过期时间点,最近更新时间在该时间点之前的文件全部过期。

  • 是否生效。

以下代码用于设置桶的生命周期。

using System;

using System.Collections.Generic;

using Amazon.S3;

using Amazon.S3.Model;

 

namespace PutLifecycleConfiguration

{

    class Program

    {

        static void Main(string[] args)

        {  

            var Ak = "xxx";

            var Sk = "xxx";

            var endpoint = "http://s3.test.com";

            AmazonS3Client serviceClient = new AmazonS3Client(Ak,Sk,

            new AmazonS3Config{ ServiceURL = endpoint });

 

            try

            {  

                PutLifecycleConfigurationResponse response;

                LifecycleConfiguration newConfiguration = new LifecycleConfiguration

            {

                Rules = new List

                {

                    // Rule to delete keys with prefix "Test-" after 5 days

                    new LifecycleRule

                    {

                        Prefix = "Test-",

                        Expiration = new LifecycleRuleExpiration { Days = 5 }

                    },

                    // Rule to delete keys in subdirectory "Logs" after 2 days

                    new LifecycleRule

                    {

                        Prefix = "Logs/",

                        Expiration = new LifecycleRuleExpiration  { Days = 2 },

                        Id = "log-file-removal"

                    }

                }

            };

            PutLifecycleConfigurationRequest putRequest = new PutLifecycleConfigurationRequest

            {

                BucketName = "xxx",

                Configuration = newConfiguration

            };

 

            response = serviceClient.PutLifecycleConfigurationAsync(putRequest).GetAwaiter().GetResult();

           

            Console.WriteLine(response.HttpStatusCode);

            

            } catch (AmazonS3Exception e) {

                Console.WriteLine(e.Message);

                throw;

            } catch (Exception e) {

                Console.WriteLine(e);

                throw;

            }

 

        }

 

    }

}