Java
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
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";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
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();
}
}
}
}
PHP
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use OSS\Model\LifecycleConfig;
use OSS\Model\LifecycleRule;
use OSS\Model\LifecycleAction;
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
$provider = new EnvironmentVariableCredentialsProvider();
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 填写存储空间名称。
$bucket= "examplebucket";
// 设置规则ID和文件前缀。
$ruleId0 = "rule0";
$matchPrefix0 = "A0/";
$ruleId1 = "rule1";
$matchPrefix1 = "A1/";
$lifecycleConfig = new LifecycleConfig();
$actions = array();
// 距最后修改时间3天后过期。
$actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DAYS, 3);
$lifecycleRule = new LifecycleRule($ruleId0, $matchPrefix0, "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
$actions = array();
// 指定日期之前创建的文件过期。
$actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DATE, '2022-10-12T00:00:00.000Z');
$lifecycleRule = new LifecycleRule($ruleId1, $matchPrefix1, "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
$ossClient->putBucketLifecycle($bucket, $lifecycleConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
Node.js
const OSS = require('ali-oss')
const client = new OSS({
// yourregion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou。
region: 'yourregion',
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// 填写存储空间名称。
bucket: 'yourbucketname'
});
async function putBucketLifecycle(lifecycle) {
try {
const result = await client.putBucketLifecycle('yourbucketname', [
lifecycle
]);
console.log(result);
} catch (e) {
console.log(e);
}
}
const lifecycle1 = {
id: 'rule1',
status: 'Enabled',
prefix: 'foo/',
expiration: {
// 指定当前版本Object距其最后修改时间3天后过期。
days: 3
}
}
putBucketLifecycle(lifecycle1)
const lifecycle2 = {
id: 'rule2',
status: 'Enabled',
prefix: 'foo/',
expiration: {
// 指定日期之前创建的文件过期。
createdBeforeDate: '2020-02-18T00:00:00.000Z'
},
}
putBucketLifecycle(lifecycle2)
const lifecycle3 = {
id: 'rule3',
status: 'Enabled',
prefix: 'foo/',
abortMultipartUpload: {
// 指定分片3天后过期。
days: 3
},
}
putBucketLifecycle(lifecycle3)
const lifecycle4 = {
id: 'rule4',
status: 'Enabled',
prefix: 'foo/',
abortMultipartUpload: {
// 指定日期之前创建的分片过期。
createdBeforeDate: '2020-02-18T00:00:00.000Z'
},
}
putBucketLifecycle(lifecycle4)
const lifecycle5 = {
id: 'rule5',
status: 'Enabled',
prefix: 'foo/',
transition: {
// 指定当前版本Object距其最后修改时间20天后转归档存储类型。
days: 20,
storageClass: 'Archive'
},
expiration: {
// 指定当前版本Object距其最后修改时间21天后过期。
days: 21
},
}
putBucketLifecycle(lifecycle5)
const lifecycle6 = {
id: 'rule6',
status: 'Enabled',
prefix: 'foo/',
transition: {
// 达到指定日期后自动将文件转为归档类型。
createdBeforeDate: '2023-02-19T00:00:00.000Z',
storageClass: 'Archive'
},
expiration: {
// 达到指定日期后自动将文件删除。
createdBeforeDate: '2023-01-18T00:00:00.000Z'
},
}
putBucketLifecycle(lifecycle6)
const lifecycle7 = {
id: 'rule7',
status: 'Enabled',
prefix: 'foo/',
expiration: {
// 设置自动移除过期删除标记。
expiredObjectDeleteMarker: true
}
}
putBucketLifecycle(lifecycle7)
const lifecycle8 = {
id: 'rule8',
status: 'Enabled',
prefix: 'foo/',
// 设置非当前版本的Object距其最后修改时间10天之后转为低频访问类型。
noncurrentVersionTransition: {
noncurrentDays: '10',
storageClass: 'IA'
}
}
putBucketLifecycle(lifecycle8)
const lifecycle9 = {
id: 'rule9',
status: 'Enabled',
prefix: 'foo/',
// 设置非当前版本的Object距其最后修改时间10天之后转为低频访问类型。
noncurrentVersionTransition: {
noncurrentDays: '10',
storageClass: 'IA'
},
// 指定规则所适用的对象标签。
tag: [{
key: 'key1',
value: 'value1'
},
{
key: 'key2',
value: 'value2'
}]
}
putBucketLifecycle(lifecycle9)
Python
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import datetime
from oss2.models import (LifecycleExpiration, LifecycleRule,
BucketLifecycle,AbortMultipartUpload,
TaggingRule, Tagging, StorageTransition,
NoncurrentVersionStorageTransition,
NoncurrentVersionExpiration)
# 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
# 填写Bucket名称,例如examplebucket。
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# 设置Object距其最后修改时间3天后过期。
rule1 = LifecycleRule('rule1', 'tests/',
status=LifecycleRule.ENABLED,
expiration=LifecycleExpiration(days=3))
# 设置Object过期规则,指定日期之前创建的文件过期。
rule2 = LifecycleRule('rule2', 'tests2/',
status=LifecycleRule.ENABLED,
expiration=LifecycleExpiration(created_before_date=datetime.date(2023, 12, 12)))
# 设置分片过期规则,分片3天后过期。
rule3 = LifecycleRule('rule3', 'tests3/',
status=LifecycleRule.ENABLED,
abort_multipart_upload=AbortMultipartUpload(days=3))
# 设置分片过期规则,指定日期之前的分片过期。
rule4 = LifecycleRule('rule4', 'tests4/',
status=LifecycleRule.ENABLED,
abort_multipart_upload = AbortMultipartUpload(created_before_date=datetime.date(2022, 12, 12)))
# 设置存储类型转换规则,指定Object在其最后修改时间20天之后转为低频访问类型,在其最后修改时间30天之后转为归档类型。
rule5 = LifecycleRule('rule5', 'tests5/',
status=LifecycleRule.ENABLED,
storage_transitions=[StorageTransition(days=20,storage_class=oss2.BUCKET_STORAGE_CLASS_IA),
StorageTransition(days=30,storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)])
# 设置匹配的标签。
tagging_rule = TaggingRule()
tagging_rule.add('key1', 'value1')
tagging_rule.add('key2', 'value2')
tagging = Tagging(tagging_rule)
# 设置存储类型转换规则,指定Object在其最后修改时间超过365天后转为ARCHIVE类型。
# rule6与以上几个规则不同的是它指定了匹配的标签,同时拥有key1=value1,key2=value2两个标签的object才会匹配此规则。
rule6 = LifecycleRule('rule6', 'tests6/',
status=LifecycleRule.ENABLED,
storage_transitions=[StorageTransition(created_before_date=datetime.date(2022, 12, 12),storage_class=oss2.BUCKET_STORAGE_CLASS_IA)],
tagging = tagging)
# rule7针对版本控制状态下的Bucket。
# 设置Object在其最后修改时间365天之后自动转为ARCHIVE类型。
# 设置自动移除过期删除标记。
# 设置非当前版本Object 12天后转为IA类型。
# 设置非当前版本Object 20天后转为ARCHIVE类型。
# 设置非当前版本Object 30天后删除。
rule7 = LifecycleRule('rule7', 'tests7/',
status=LifecycleRule.ENABLED,
storage_transitions=[StorageTransition(days=365, storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)],
expiration=LifecycleExpiration(expired_detete_marker=True),
noncurrent_version_sotrage_transitions =
[NoncurrentVersionStorageTransition(12, oss2.BUCKET_STORAGE_CLASS_IA),
NoncurrentVersionStorageTransition(20, oss2.BUCKET_STORAGE_CLASS_ARCHIVE)],
noncurrent_version_expiration = NoncurrentVersionExpiration(30))
lifecycle = BucketLifecycle([rule1, rule2, rule3, rule4, rule5, rule6, rule7])
bucket.put_bucket_lifecycle(lifecycle)
C#
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// 填写Bucket名称,例如examplebucket。
var bucketName = "examplebucket";
// 创建OSSClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
var setBucketLifecycleRequest = new SetBucketLifecycleRequest(bucketName);
// 创建第1条生命周期规则。
LifecycleRule lcr1 = new LifecycleRule()
{
ID = "delete obsoleted files",
Prefix = "obsoleted/",
Status = RuleStatus.Enabled,
ExpriationDays = 3,
Tags = new Tag[1]
};
// 设置标签。
var tag1 = new Tag
{
Key = "project",
Value = "projectone"
};
lcr1.Tags[0] = tag1;
// 创建第2条生命周期规则。
LifecycleRule lcr2 = new LifecycleRule()
{
ID = "delete temporary files",
Prefix = "temporary/",
Status = RuleStatus.Enabled,
ExpriationDays = 20,
Tags = new Tag[1]
};
// 设置标签。
var tag2 = new Tag
{
Key = "user",
Value = "jsmith"
};
lcr2.Tags[0] = tag2;
// 设置碎片在距最后修改时间30天后过期。
lcr2.AbortMultipartUpload = new LifecycleRule.LifeCycleExpiration()
{
Days = 30
};
LifecycleRule lcr3 = new LifecycleRule();
lcr3.ID = "only NoncurrentVersionTransition";
lcr3.Prefix = "test1";
lcr3.Status = RuleStatus.Enabled;
lcr3.NoncurrentVersionTransitions = new LifecycleRule.LifeCycleNoncurrentVersionTransition[2]
{
// 设置非当前版本的Object距最后修改时间90天之后转为低频访问类型。
new LifecycleRule.LifeCycleNoncurrentVersionTransition(){
StorageClass = StorageClass.IA,
NoncurrentDays = 90
},
// 设置非当前版本的Object距最后修改时间180天之后转为归档类型。
new LifecycleRule.LifeCycleNoncurrentVersionTransition(){
StorageClass = StorageClass.Archive,
NoncurrentDays = 180
}
};
setBucketLifecycleRequest.AddLifecycleRule(lcr1);
setBucketLifecycleRequest.AddLifecycleRule(lcr2);
setBucketLifecycleRequest.AddLifecycleRule(lcr3);
// 设置生命周期规则。
client.SetBucketLifecycle(setBucketLifecycleRequest);
Console.WriteLine("Set bucket:{0} Lifecycle succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Android-Java
PutBucketLifecycleRequest request = new PutBucketLifecycleRequest();
request.setBucketName("examplebucket");
BucketLifecycleRule rule1 = new BucketLifecycleRule();
// 设置规则ID和文件前缀。
rule1.setIdentifier("1");
rule1.setPrefix("A");
// 设置是否执行生命周期规则。如果值为true,则OSS会定期执行该规则;如果值为false,则OSS会忽略该规则。
rule1.setStatus(true);
// 距最后修改时间200天后过期。
rule1.setDays("200");
// 30天后自动转为归档存储类型(Archive)
rule1.setArchiveDays("30");
// 未完成分片3天后过期。
rule1.setMultipartDays("3");
// 15天后自动转为低频存储类型(IA)。
rule1.setIADays("15");
BucketLifecycleRule rule2 = new BucketLifecycleRule();
rule2.setIdentifier("2");
rule2.setPrefix("B");
rule2.setStatus(true);
rule2.setDays("300");
rule2.setArchiveDays("30");
rule2.setMultipartDays("3");
rule2.setIADays("15");
ArrayList<BucketLifecycleRule> lifecycleRules = new ArrayList<BucketLifecycleRule>();
lifecycleRules.add(rule1);
lifecycleRules.add(rule2);
request.setLifecycleRules(lifecycleRules);
OSSAsyncTask task = oss.asyncPutBucketLifecycle(request, new OSSCompletedCallback<PutBucketLifecycleRequest, PutBucketLifecycleResult>() {
@Override
public void onSuccess(PutBucketLifecycleRequest request, PutBucketLifecycleResult result) {
OSSLog.logInfo("code::"+result.getStatusCode());
}
@Override
public void onFailure(PutBucketLifecycleRequest request, ClientException clientException, ServiceException serviceException) {
OSSLog.logError("error: "+serviceException.getRawMessage());
}
});
task.waitUntilFinished();
Go
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main() {
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 创建OSSClient实例。
// yourEndpoint填写Bucket对应的Endpoint,以华东1(杭州)为例,填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 填写存储空间名称。
bucketName := "examplebucket"
// 指定生命周期规则1,并在规则中指定前缀为foo的文件在距离最后一次修改时间3天后过期。
rule1 := oss.BuildLifecycleRuleByDays("rule1", "foo/", true, 3)
// 在受版本控制状态下的Object仅有删除标记的情况下,自动删除删除标记。
deleteMark := true
expiration := oss.LifecycleExpiration{
ExpiredObjectDeleteMarker: &deleteMark,
}
// 非当前版本Object超过30天后过期删除。
versionExpiration := oss.LifecycleVersionExpiration{
NoncurrentDays: 30,
}
// 非当前版本Object超过10天后转为IA存储类型。
versionTransition := oss.LifecycleVersionTransition{
NoncurrentDays: 10,
StorageClass: "IA",
}
// 指定生命周期规则2。
rule2 := oss.LifecycleRule{
ID: "rule2",
Prefix: "yourObjectPrefix",
Status: "Enabled",
Expiration: &expiration,
NonVersionExpiration: &versionExpiration,
NonVersionTransitions: []oss.LifecycleVersionTransition{
versionTransition,
},
}
// 指定生命周期规则3,对标签键为tag1、标签值为value1的文件,距文件最后一次修改时间3天后过期。
rule3 := oss.LifecycleRule{
ID: "rule3",
Prefix: "",
Status: "Enabled",
Tags: []oss.Tag{
oss.Tag{
Key: "tag1",
Value: "value1",
},
},
Expiration: &oss.LifecycleExpiration{Days: 3},
}
// 设置生命周期规则。
rules := []oss.LifecycleRule{rule1, rule2, rule3}
err = client.SetBucketLifecycle(bucketName, rules)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
C++
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/*初始化OSS账号信息。*/
/*yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
std::string Endpoint = "yourEndpoint";
/*填写Bucket名称,例如examplebucket。*/
std::string BucketName = "examplebucket";
/*初始化网络等资源。*/
InitializeSdk();
ClientConfiguration conf;
/* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
SetBucketLifecycleRequest request(BucketName);
std::string date("2022-10-12T00:00:00.000Z");
/*设置标签。*/
Tagging tagging;
tagging.addTag(Tag("key1", "value1"));
tagging.addTag(Tag("key2", "value2"));
/*指定生命周期规则。*/
auto rule1 = LifecycleRule();
rule1.setID("rule1");
rule1.setPrefix("test1/");
rule1.setStatus(RuleStatus::Enabled);
rule1.setExpiration(3);
rule1.setTags(tagging.Tags());
/*指定过期时间。*/
auto rule2 = LifecycleRule();
rule2.setID("rule2");
rule2.setPrefix("test2/");
rule2.setStatus(RuleStatus::Disabled);
rule2.setExpiration(date);
/*rule3为针对版本控制状态下的Bucket的生命周期规则。*/
auto rule3 = LifecycleRule();
rule3.setID("rule3");
rule3.setPrefix("test3/");
rule3.setStatus(RuleStatus::Disabled);
/*设置Object距其最后修改时间365天之后自动转为归档类型。*/
auto transition = LifeCycleTransition();
transition.Expiration().setDays(365);
transition.setStorageClass(StorageClass::Archive);
rule3.addTransition(transition);
/*设置自动移除过期删除标记。*/
rule3.setExpiredObjectDeleteMarker(true);
/*设置非当前版本的Object距最后修改时间10天之后转为低频访问类型。*/
auto transition1 = LifeCycleTransition();
transition1.Expiration().setDays(10);
transition1.setStorageClass(StorageClass::IA);
/*设置非当前版本的Object距最后修改时间20天之后转为归档类型。*/
auto transition2 = LifeCycleTransition();
transition2.Expiration().setDays(20);
transition2.setStorageClass(StorageClass::Archive);
/*设置Object在其成为非当前版本30天之后删除。*/
auto expiration = LifeCycleExpiration(30);
rule3.setNoncurrentVersionExpiration(expiration);
LifeCycleTransitionList noncurrentVersionStorageTransitions{transition1, transition2};
rule3.setNoncurrentVersionTransitionList(noncurrentVersionStorageTransitions);
/*设置生命周期规则。*/
LifecycleRuleList list{rule1, rule2, rule3};
request.setLifecycleRules(list);
auto outcome = client.SetBucketLifecycle(request);
if (!outcome.isSuccess()) {
/*异常处理 */
std::cout << "SetBucketLifecycle fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/*释放网络等资源。*/
ShutdownSdk();
return 0;
}
C
#include "oss_api.h"
#include "aos_http_io.h"
/* yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
const char *endpoint = "yourEndpoint";
/* 填写Bucket名称,例如examplebucket。*/
const char *bucket_name = "examplebucket";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* 用char*类型的字符串初始化aos_string_t类型。*/
aos_str_set(&options->config->endpoint, endpoint);
/* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* 是否使用cname域名访问OSS服务。0表示不使用。*/
options->config->is_cname = 0;
/* 用于设置网络相关参数,比如超时时间等。*/
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* 在程序入口调用aos_http_io_initialize方法来初始化网络、内存等全局资源。*/
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* 用于内存管理的内存池(pool),等价于apr_pool_t。其实现代码在apr库中。*/
aos_pool_t *pool;
/* 重新创建一个内存池,第二个参数是NULL,表示没有继承其它内存池。*/
aos_pool_create(&pool, NULL);
/* 创建并初始化options,该参数包括endpoint、access_key_id、acces_key_secret、is_cname、curl等全局配置信息。*/
oss_request_options_t *oss_client_options;
/* 在内存池中分配内存给options。*/
oss_client_options = oss_request_options_create(pool);
/* 初始化Client的选项oss_client_options。*/
init_options(oss_client_options);
/* 初始化参数。*/
aos_string_t bucket;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_list_t lifecycle_rule_list;
aos_str_set(&bucket, bucket_name);
aos_list_init(&lifecycle_rule_list);
/* 指定过期天数。*/
oss_lifecycle_rule_content_t *rule_content_days = oss_create_lifecycle_rule_content(pool);
aos_str_set(&rule_content_days->id, "rule-1");
/* 设置文件前缀。*/
aos_str_set(&rule_content_days->prefix, "dir1");
aos_str_set(&rule_content_days->status, "Enabled");
rule_content_days->days = 3;
aos_list_add_tail(&rule_content_days->node, &lifecycle_rule_list);
/* 指定过期时间。*/
oss_lifecycle_rule_content_t *rule_content_date = oss_create_lifecycle_rule_content(pool);
aos_str_set(&rule_content_date->id, "rule-2");
aos_str_set(&rule_content_date->prefix, "dir2");
aos_str_set(&rule_content_date->status, "Enabled");
/* 过期时间格式为UTC。
aos_str_set(&rule_content_date->date, "2023-10-11T00:00:00.000Z");
aos_list_add_tail(&rule_content_date->node, &lifecycle_rule_list);
/* 设置生命周期规则。*/
resp_status = oss_put_bucket_lifecycle(oss_client_options, &bucket, &lifecycle_rule_list, &resp_headers);
if (aos_status_is_ok(resp_status)) {
printf("put bucket lifecycle succeeded\n");
} else {
printf("put bucket lifecycle failed, code:%d, error_code:%s, error_msg:%s, request_id:%s\n",
resp_status->code, resp_status->error_code, resp_status->error_msg, resp_status->req_id);
}
/* 释放内存池,相当于释放了请求过程中各资源分配的内存。*/
aos_pool_destroy(pool);
/* 释放之前分配的全局资源。*/
aos_http_io_deinitialize();
return 0;
}
Ruby
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# 填写Bucket名称。
bucket = client.get_bucket('examplebucket')
# 设置生命周期规则。
bucket.lifecycle = [
Aliyun::OSS::LifeCycleRule.new(
:id => 'rule1', :enable => true, :prefix => 'foo/', :expiry => 3),
Aliyun::OSS::LifeCycleRule.new(
:id => 'rule2', :enable => false, :prefix => 'bar/', :expiry => Date.new(2016, 1, 1))
]