OSS允许用户对Bucket设置生命周期规则,以自动淘汰过期掉的文件,节省存储空间。针对不同前缀的文件,用户可以同时设置多条规则。一条规则包含:
- 规则ID,用于标识一条规则,不能重复
- 受影响的文件前缀,此规则只作用于符合前缀的文件
- 过期时间,有三种指定方式:
-
指定距文件最后修改时间N天过期
- 指定日期创建前的文件过期,之后的不过期
- 指定在具体的某一天过期,即在那天之后符合前缀的文件将会过期,而不论文件的最后修改时间。不推荐使用。
- 是否生效
上面的过期规则对用户上传的文件有效。用户通过uploadPart上传的分片,也可以设置过期规则。Multipart的Lifecycle和文件的类似,过期时间支持1、2两种,不支持3,生效是以init Multipart upload的时间为准。
更多关于生命周期的内容请参考
文件生命周期
设置生命周期规则
通过OSSClient.setBucketLifecycle来设置生命周期规则:
- SetBucketLifecycleRequest request = new SetBucketLifecycleRequest("bucketName");
- // 最近修改3天后过期
- request.AddLifecycleRule(new LifecycleRule(ruleId0, matchPrefix0, RuleStatus.Enabled, 3));
- // 特定日期后过期
- request.AddLifecycleRule(new LifecycleRule(ruleId1, matchPrefix1, RuleStatus.Enabled,
- DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z")));
- // 特定日期前创建的文件过期
- LifecycleRule rule = new LifecycleRule(ruleId4, matchPrefix4, RuleStatus.Enabled);
- rule.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
- request.AddLifecycleRule(rule);
- // Multipart3天后过期
- rule = new LifecycleRule(ruleId2, matchPrefix2, RuleStatus.Enabled);
- LifecycleRule.AbortMultipartUpload abortMultipartUpload = rule.new AbortMultipartUpload();
- abortMultipartUpload.setExpirationDays(3);
- rule.setAbortMultipartUpload(abortMultipartUpload);
- request.AddLifecycleRule(rule);
- // 特定日期前的Multipart过期
- rule = new LifecycleRule(ruleId3, matchPrefix3, RuleStatus.Enabled);
- abortMultipartUpload = rule.new AbortMultipartUpload();
- abortMultipartUpload.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
- rule.setAbortMultipartUpload(abortMultipartUpload);
- request.AddLifecycleRule(rule);
- ossClient.setBucketLifecycle(request);
查看生命周期规则
通过OSSClient.GetBucketLifecycle来查看生命周期规则:
- List<LifecycleRule> rules = ossClient.getBucketLifecycle("bucketName");
- for (LifecycleRule rule : rules) {
- System.out.println(rule.getId());
- System.out.println(rule.getPrefix());
- System.out.println(rule.getExpirationDays());
- }
清空生命周期规则
通过OSSClient.DeleteBucketLifecycle设置来清空生命周期规则:
- ossClient.deleteBucketLifecycle("bucketName");