Es posible que algunos datos cargados en Object Storage Service (OSS) no se consulten con frecuencia, pero deban conservarse en almacenamiento en frío por requisitos de cumplimiento normativo o archivado. Asimismo, podría ser necesario eliminar en lotes los datos que ya no son necesarios para reducir los costos de almacenamiento. En estos casos, configure reglas de ciclo de vida basadas en la fecha de última modificación para convertir periódicamente los datos activos en datos fríos o eliminar los objetos no deseados.
Notas
Antes de configurar reglas de ciclo de vida basadas en la fecha de última modificación de los objetos, familiarícese con esta función. Para obtener más información, consulte Lifecycle rules based on the last modified time.
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región donde se encuentra OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación mediante credenciales de Security Token Service (STS), consulte Initialization (C# SDK V1).
Para configurar reglas de ciclo de vida, debe contar con el permiso
oss:PutBucketLifecycle. Para consultar reglas de ciclo de vida, requiere el permisooss:GetBucketLifecycle. Para borrar reglas de ciclo de vida, necesita el permisooss:DeleteBucketLifecycle. Para obtener más información, consulte Grant a custom policy.
Configuración de reglas de ciclo de vida para un bucket
El siguiente código de ejemplo muestra cómo configurar reglas de ciclo de vida basadas en la fecha de última modificación para un bucket llamado examplebucket. Para modificar las reglas de ciclo de vida, siga las instrucciones descritas en How do I change the configurations of one or more lifecycle rules?.
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);
}
Consulta de las reglas de ciclo de vida de un bucket
El siguiente código de ejemplo muestra cómo consultar las reglas de ciclo de vida configuradas para 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);
}
Eliminación de todas las reglas de ciclo de vida de un bucket
El siguiente código de ejemplo muestra cómo eliminar las reglas de ciclo de vida configuradas para examplebucket. Para eliminar una o más reglas de ciclo de vida, siga las instrucciones descritas en How do I delete one or more lifecycle rules?.
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);
}
Referencias
Para consultar el código de ejemplo completo utilizado para gestionar reglas de ciclo de vida, visite GitHub.
Para obtener más información sobre la operación de API que permite configurar reglas de ciclo de vida, consulte PutBucketLifecycle.
Para obtener más información sobre la operación de API que permite consultar reglas de ciclo de vida, consulte GetBucketLifecycle.
Para obtener más información sobre la operación de API que permite eliminar reglas de ciclo de vida, consulte DeleteBucketLifecycle.