OSS支持设置生命周期(Lifecycle)规则,自动删除过期的文件(Object)和碎片,或将到期的文件转储为低频或归档存储类型,从而节省存储费用。本文介绍如何管理存储空间(Bucket)的生命周期规则。

注意事项

  • 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见访问域名和数据中心
  • 本文以OSS域名新建OSSClient为例。如果您希望通过自定义域名、STS等方式新建OSSClient,请参见新建OSSClient
  • 要设置生命周期规则,您必须有oss:PutBucketLifecycle权限;要查看生命周期规则,您必须有oss:GetBucketLifecycle规则;要清空生命周期规则,您必须有oss:DeleteBucketLifecycle权限。具体操作,请参见为RAM用户授权自定义的权限策略

设置生命周期规则

  • 按照标签匹配和前缀匹配的方式设置生命周期规则

    以下代码用于为examplebucket存储空间按照标签匹配和前缀匹配的方式设置生命周期规则。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.common.utils.DateUtil;
    import com.aliyun.oss.model.LifecycleRule;
    import com.aliyun.oss.model.SetBucketLifecycleRequest;
    import com.aliyun.oss.model.StorageClass;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // 创建SetBucketLifecycleRequest。
                SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
    
                // 设置规则ID。
                String ruleId0 = "rule0";
                // 设置文件匹配前缀。
                String matchPrefix0 = "A0/";
                // 设置要匹配的标签。
                Map<String, String> matchTags0 = new HashMap<String, String>();
                // 依次填写要匹配标签的键(例如owner)和值(例如John)。
                matchTags0.put("owner", "John");
    
    
                String ruleId1 = "rule1";
                String matchPrefix1 = "A1/";
                Map<String, String> matchTags1 = new HashMap<String, String>();
                matchTags1.put("type", "document");
    
                String ruleId2 = "rule2";
                String matchPrefix2 = "A2/";
    
                String ruleId3 = "rule3";
                String matchPrefix3 = "A3/";
    
                String ruleId4 = "rule4";
                String matchPrefix4 = "A4/";
    
                String ruleId5 = "rule5";
                String matchPrefix5 = "A5/";
    
                String ruleId6 = "rule6";
                String matchPrefix6 = "A6/";
    
                // 距最后修改时间3天后过期。
                LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
                rule.setTags(matchTags0);
                request.AddLifecycleRule(rule);
    
                // 指定日期之前创建的文件过期。
                rule = new LifecycleRule(ruleId1, matchPrefix1, LifecycleRule.RuleStatus.Enabled);
                rule.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
                rule.setTags(matchTags1);
                request.AddLifecycleRule(rule);
    
                // 分片3天后过期。
                rule = new LifecycleRule(ruleId2, matchPrefix2, LifecycleRule.RuleStatus.Enabled);
                LifecycleRule.AbortMultipartUpload abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
                abortMultipartUpload.setExpirationDays(3);
                rule.setAbortMultipartUpload(abortMultipartUpload);
                request.AddLifecycleRule(rule);
    
                // 指定日期之前的分片过期。
                rule = new LifecycleRule(ruleId3, matchPrefix3, LifecycleRule.RuleStatus.Enabled);
                abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
                abortMultipartUpload.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
                rule.setAbortMultipartUpload(abortMultipartUpload);
                request.AddLifecycleRule(rule);
    
                // 距最后修改时间10天后转低频访问存储类型,距最后修改时间30天后转归档存储类型。
                rule = new LifecycleRule(ruleId4, matchPrefix4, LifecycleRule.RuleStatus.Enabled);
                List<LifecycleRule.StorageTransition> storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
                LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
                storageTransition.setStorageClass(StorageClass.IA);
                storageTransition.setExpirationDays(10);
                storageTransitions.add(storageTransition);
                storageTransition = new LifecycleRule.StorageTransition();
                storageTransition.setStorageClass(StorageClass.Archive);
                storageTransition.setExpirationDays(30);
                storageTransitions.add(storageTransition);
                rule.setStorageTransition(storageTransitions);
                request.AddLifecycleRule(rule);
    
                // 指定最后修改日期在2022年10月12日之前的文件转为归档存储。
                rule = new LifecycleRule(ruleId5, matchPrefix5, LifecycleRule.RuleStatus.Enabled);
                storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
                storageTransition = new LifecycleRule.StorageTransition();
    
                storageTransition.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
    
                storageTransition.setStorageClass(StorageClass.Archive);
                storageTransitions.add(storageTransition);
                rule.setStorageTransition(storageTransitions);
                request.AddLifecycleRule(rule);
    
                // rule6针对版本控制状态下的Bucket。
                rule = new LifecycleRule(ruleId6, matchPrefix6, LifecycleRule.RuleStatus.Enabled);
                // 设置Object相对最后修改时间365天之后自动转为归档文件。
                storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
                storageTransition = new LifecycleRule.StorageTransition();
                storageTransition.setStorageClass(StorageClass.Archive);
                storageTransition.setExpirationDays(365);
                storageTransitions.add(storageTransition);
                rule.setStorageTransition(storageTransitions);
                // 设置自动移除过期删除标记。
                rule.setExpiredDeleteMarker(true);
                // 设置非当前版本的object距最后修改时间10天之后转为低频访问类型。
                LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition =
                        new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(10).withStrorageClass(StorageClass.IA);
                // 设置非当前版本的Object距最后修改时间20天之后转为归档类型。
                LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition2 =
                        new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(20).withStrorageClass(StorageClass.Archive);
                // 设置非当前版本Object 30天后删除。
                LifecycleRule.NoncurrentVersionExpiration noncurrentVersionExpiration = new LifecycleRule.NoncurrentVersionExpiration().withNoncurrentDays(30);
                List<LifecycleRule.NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitions = new ArrayList<LifecycleRule.NoncurrentVersionStorageTransition>();
                noncurrentVersionStorageTransitions.add(noncurrentVersionStorageTransition2);
                rule.setStorageTransition(storageTransitions);
                rule.setNoncurrentVersionExpiration(noncurrentVersionExpiration);
                rule.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitions);
                request.AddLifecycleRule(rule);
    
                // 发起设置生命周期规则请求。
                ossClient.setBucketLifecycle(request);
    
                // 查看生命周期规则。
                List<LifecycleRule> listRules = ossClient.getBucketLifecycle(bucketName);
                for(LifecycleRule rules : listRules){
                    System.out.println("ruleId="+rules.getId()+", matchPrefix="+rules.getPrefix());
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 按照整个Bucket设置生命周期规则
    以下代码用于为examplebucket存储空间按照整个Bucket设置生命周期规则。
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.LifecycleRule;
    import com.aliyun.oss.model.SetBucketLifecycleRequest;
    import java.util.List;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // 创建SetBucketLifecycleRequest。
                SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
    
                // 设置规则ID。
                String ruleId0 = "rule0";
                // 如果文件匹配前缀设置为空,则表示此规则适用于Bucket中的所有Object。
                String matchPrefix0 = null;
    
                // 距最后修改时间3天后过期。
                LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
                request.AddLifecycleRule(rule);
    
                // 发起设置生命周期规则请求。
                ossClient.setBucketLifecycle(request);
    
                // 查看生命周期规则。
                List<LifecycleRule> listRules = ossClient.getBucketLifecycle(bucketName);
                for(LifecycleRule rules : listRules){
                    System.out.println("ruleId="+rules.getId()+", matchPrefix="+rules.getPrefix()+", expirationDays="+rules.getExpirationDays());
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

查看生命周期规则

以下代码用于查看examplebucket存储空间的生命周期规则。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.LifecycleRule;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取生命周期规则。
            List<LifecycleRule> rules = ossClient.getBucketLifecycle(bucketName);

            // 查看生命周期规则。
            for (LifecycleRule r : rules) {
                System.out.println("================");

                // 查看规则ID。
                System.out.println("rule id: " + r.getId());

                // 查看规则状态。
                System.out.println("rule status: " + r.getStatus());

                // 查看规则前缀。
                System.out.println("rule prefix: " + r.getPrefix());

                // 查看规则标签。
                if (r.hasTags()) {
                    System.out.println("rule tagging: "+ r.getTags().toString());
                }

                // 查看过期天数规则。
                if (r.hasExpirationDays()) {
                    System.out.println("rule expiration days: " + r.getExpirationDays());
                }

                // 查看过期日期规则。
                if (r.hasCreatedBeforeDate()) {
                    System.out.println("rule expiration create before days: " + r.getCreatedBeforeDate());
                }

                // 查看过期分片规则。
                if(r.hasAbortMultipartUpload()) {
                    if(r.getAbortMultipartUpload().hasExpirationDays()) {
                        System.out.println("rule abort uppart days: " + r.getAbortMultipartUpload().getExpirationDays());
                    }

                    if (r.getAbortMultipartUpload().hasCreatedBeforeDate()) {
                        System.out.println("rule abort uppart create before date: " + r.getAbortMultipartUpload().getCreatedBeforeDate());
                    }
                }

                // 查看存储类型转换规则。
                if (r.getStorageTransition().size() > 0) {
                    for (LifecycleRule.StorageTransition transition : r.getStorageTransition()) {
                        if (transition.hasExpirationDays()) {
                            System.out.println("rule storage trans days: " + transition.getExpirationDays() +
                                    " trans storage class: " + transition.getStorageClass());
                        }

                        if (transition.hasCreatedBeforeDate()) {
                            System.out.println("rule storage trans before create date: " + transition.getCreatedBeforeDate());
                        }
                    }
                }

                // 查看是否自动删除过期删除标记。
                if (r.hasExpiredDeleteMarker()) {
                    System.out.println("rule expired delete marker: " + r.getExpiredDeleteMarker());
                }

                // 查看非当前版本Object存储类型转换规则。
                if (r.hasNoncurrentVersionStorageTransitions()) {
                    for (LifecycleRule.NoncurrentVersionStorageTransition transition : r.getNoncurrentVersionStorageTransitions()) {
                        System.out.println("rule noncurrent versions trans days:" + transition.getNoncurrentDays() +
                                " trans storage class: " + transition.getStorageClass());
                    }
                }

                // 查看非当前版本Object过期规则。
                if (r.hasNoncurrentVersionExpiration()) {
                    System.out.println("rule noncurrent versions expiration days:" + r.getNoncurrentVersionExpiration().getNoncurrentDays());
                }
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

清空生命周期规则

以下代码用于清空examplebucket存储空间的生命周期规则。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            ossClient.deleteBucketLifecycle(bucketName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

相关文档