Este tópico descreve como gerencie o ciclo de vida de dados do Object Storage Service (OSS) usando o OSS SDK for PHP V2.
Informações gerais
Nem todos os dados armazenados no OSS são acessados com frequência. No entanto, dados acessados com pouca frequência precisam ser retidos para atender a regulamentações de dados ou requisitos de arquivamento. O OSS permite configure regras de ciclo de vida que automatizam o gerenciamento do ciclo de vida dos seus dados. Há dois tipos de regras de ciclo de vida disponíveis:
Regra de ciclo de vida baseada na hora da última modificação. Esse tipo de regra pode ser usado para exclua dados que não foram modificados por um longo período ou para movê-los para uma classe de armazenamento mais econômica para dados frios.
Regra de ciclo de vida baseada na hora do último acesso. Esse tipo de regra identifica padrões de acesso a dados e move automaticamente dados frios para uma classe de armazenamento mais econômica. Essa abordagem viabiliza o armazenamento em camadas para dados quentes e frios, reduzindo os custos de armazenamento.
Observações
Antes de configure uma regra de ciclo de vida baseada na hora da última modificação ou do último acesso, verifique se você está familiarizado com o recurso de gerenciamento de ciclo de vida. Para obter mais informações, consulte Lifecycle rules based on last modification time e Lifecycle rules based on last access time.
O código de exemplo neste tópico usa o ID de região
cn-hangzhouda região china (Hangzhou). Por padrão, o endpoint público é usado para acessar recursos em um bucket. Para acessar recursos no bucket a partir de outros serviços da Alibaba Cloud na mesma região em que o bucket está localizado, use o endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.Para configure regras de ciclo de vida, é necessária a permissão
oss:PutBucketLifecycle. Para consultar regras de ciclo de vida, é necessária a permissãooss:GetBucketLifecycle. Para limpar regras de ciclo de vida, é necessária a permissãooss:DeleteBucketLifecycle. Para obter mais informações, consulte Grant a custom policy.
Configurar regras de ciclo de vida
Esta seção fornece exemplos de código que configure regras de ciclo de vida para um bucket com base na hora da última modificação ou do último acesso. Também é possível modify one or more of the lifecycle rules configuradas para um bucket.
Configurar uma regra de ciclo de vida baseada na hora da última modificação para alterar a classe de armazenamento de objetos com o prefixo de nome especifique
O código de exemplo a seguir configure uma regra de ciclo de vida baseada na hora da última modificação dos objetos para alterar a classe de armazenamento de objetos com o prefixo de nome especifique:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Define a lifecycle rule that moves objects whose names are prefixed with "log/" to IA 30 days after they were last modified.
$lifecycleRule = new Oss\Models\LifecycleRule(
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'IA' // Change to IA.
)
),
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Configurar uma regra de ciclo de vida baseada na hora da última modificação para objetos sem o prefixo de nome ou tags especifique
O código de exemplo a seguir configure uma regra de ciclo de vida que move objetos sem o prefixo de nome "log" ou sem a tag "key1:value1" para Infrequent Access (IA) 30 dias após a última modificação e os expira 100 dias após a hora da última modificação:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
$lifecycleRule = new Oss\Models\LifecycleRule(
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'Archive' // Change the storage class to Archive.
)
),
filter: new Oss\Models\LifecycleRuleFilter( // Specify filters.
not: new Oss\Models\LifecycleRuleNot( // Specify exclusion filters.
prefix: 'log', // Exclude objects whose names contain the "log" prefix.
tag: new Oss\Models\Tag( // Specify tag filters.
key: 'key1',
value: 'value1'
)
)
),
expiration: new Oss\Models\LifecycleRuleExpiration(
days: 100 // Set the object expiration time to 100 days.
)
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Configurar uma regra de ciclo de vida baseada na hora do último acesso para alterar a classe de armazenamento
O código de exemplo a seguir configure uma regra de ciclo de vida baseada na hora do último acesso para alterar a classe de armazenamento:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
{}
$lifecycleRule = new Oss\Models\LifecycleRule(
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'IA', // Change to IA.
isAccessTime: 'true', // Trigger the change based on the last access time.
returnToStdWhenVisit: 'true' // Return to the Standard storage class after they are accessed.
)
),
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Consultar regras de ciclo de vida
O código a seguir consulta as regras de ciclo de vida configure para um bucket:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request to query lifecycle rules.
$request = new Oss\Models\GetBucketLifecycleRequest(bucket: $bucket);
// Call the getBucketLifecycle method to query lifecycle rules.
$result = $client->getBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL . // The request ID.
'lifecycle:' . var_export($result->lifecycleConfiguration, true) . PHP_EOL // The lifecycle rules.
);
Limpar regras de ciclo de vida
O código de exemplo a seguir limpa as regras de ciclo de vida de um bucket. Para exclua uma ou mais regras de ciclo de vida específicas, siga as instruções em Delete lifecycle rules
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request to delete lifecycle rules of a bucket.
$request = new Oss\Models\DeleteBucketLifecycleRequest(bucket: $bucket);
// Call the deleteBucketLifecycle method to delete lifecycle rules.
$result = $client->deleteBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Referências
Para obter mais informações sobre a operação de API que configure uma regra de ciclo de vida, consulte PutBucketLifecycle.
Para obter mais informações sobre a operação de API que consulta regras de ciclo de vida, consulte GetBucketLifecycle.
Para obter mais informações sobre a operação de API que exclui regras de ciclo de vida, consulte DeleteBucketLifecycle.