Alguns dados enviados ao Object Storage Service (OSS) podem ter acesso pouco frequente, mas ainda exigem armazenamento frio para atender a requisitos de conformidade ou arquivamento. Além disso, você pode precisar excluir dados desnecessários em lote para reduzir custos de armazenamento. Nesses casos, configure regras de ciclo de vida com base na última modificação para converter periodicamente dados quentes em frios ou remover objetos indesejados.
Observações
Antes de configurar regras de ciclo de vida com base na última modificação dos objetos, familiarize-se com esse recurso. Para mais informações, consulte Regras de ciclo de vida com base na última modificação.
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
O exemplo abaixo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Inicialização (C# SDK V1).
A configuração de regras de ciclo de vida exige a permissão
oss:PutBucketLifecycle. A consulta requer a permissãooss:GetBucketLifecycle, enquanto a limpeza das regras demanda a permissãooss:DeleteBucketLifecycle. Para mais informações, consulte Conceder uma política personalizada.
Configurar regras de ciclo de vida para um bucket
O código de exemplo a seguir mostra como configurar regras de ciclo de vida com base na última modificação para um bucket chamado examplebucket. Para modificar regras existentes, siga as instruções em Como alterar as configurações de uma ou mais regras de ciclo de vida?
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
var setBucketLifecycleRequest = new SetBucketLifecycleRequest(bucketName);
// Create the first lifecycle rule.
LifecycleRule lcr1 = new LifecycleRule()
{
ID = "delete obsoleted files",
Prefix = "obsoleted/",
Status = RuleStatus.Enabled,
ExpriationDays = 3,
Tags = new Tag[1]
};
// Specify a tag for the rule.
var tag1 = new Tag
{
Key = "project",
Value = "projectone"
};
lcr1.Tags[0] = tag1;
// Create the second lifecycle rule.
LifecycleRule lcr2 = new LifecycleRule()
{
ID = "delete temporary files",
Prefix = "temporary/",
Status = RuleStatus.Enabled,
ExpriationDays = 20,
Tags = new Tag[1]
};
// Specify a tag for the rule.
var tag2 = new Tag
{
Key = "user",
Value = "jsmith"
};
lcr2.Tags[0] = tag2;
// Specify that parts expire 30 days after they are last modified.
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]
{
// Specify that the storage classes of the previous versions of objects are converted to IA 90 days after they are last modified.
new LifecycleRule.LifeCycleNoncurrentVersionTransition(){
StorageClass = StorageClass.IA,
NoncurrentDays = 90
},
// Specify that the storage classes of the previous versions of objects are converted to Archive 180 days after they are last modified.
new LifecycleRule.LifeCycleNoncurrentVersionTransition(){
StorageClass = StorageClass.Archive,
NoncurrentDays = 180
}
};
setBucketLifecycleRequest.AddLifecycleRule(lcr1);
setBucketLifecycleRequest.AddLifecycleRule(lcr2);
setBucketLifecycleRequest.AddLifecycleRule(lcr3);
// Configure lifecycle rules.
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);
}
Consultar as regras de ciclo de vida de um bucket
O exemplo de código abaixo ilustra como consultar as regras de ciclo de vida configuradas no examplebucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Query the lifecycle rules of the bucket.
var rules = client.GetBucketLifecycle(bucketName);
Console.WriteLine("Get bucket:{0} Lifecycle succeeded ", bucketName);
foreach (var rule in rules)
{
Console.WriteLine("ID: {0}", rule.ID);
Console.WriteLine("Prefix: {0}", rule.Prefix);
Console.WriteLine("Status: {0}", rule.Status);
// Query the tags that are specified for the lifecycle rules.
foreach (var tag in rule.Tags)
{
Console.WriteLine("key:{0}, value:{1}", tag.Key, tag.Value);
}
// Query the expiration rule for the previous versions of objects.
foreach (var version in rule.NoncurrentVersionTransitions)
{
Console.WriteLine("expiration day:{0}, storage class:{1}", version.NoncurrentDays, version.StorageClass);
}
if (rule.ExpriationDays.HasValue)
Console.WriteLine("ExpirationDays: {0}", rule.ExpriationDays);
}
}
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);
}
Excluir todas as regras de ciclo de vida de um bucket
O código a seguir exemplifica como excluir as regras de ciclo de vida do examplebucket. Para remover apenas regras específicas, siga as orientações em Como excluir uma ou mais regras de ciclo de vida?
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Delete the lifecycle rules.
client.DeleteBucketLifecycle(bucketName);
Console.WriteLine("Delete 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);
}
Referências
Acesse o código de exemplo completo para gerenciamento de regras de ciclo de vida no GitHub.
Para detalhes sobre a operação de API usada na configuração de regras de ciclo de vida, consulte PutBucketLifecycle.
Saiba mais sobre a operação de API para consulta de regras de ciclo de vida em GetBucketLifecycle.
Informações adicionais sobre a operação de API para exclusão de regras de ciclo de vida estão disponíveis em DeleteBucketLifecycle.