Todos os produtos
Search
Central de documentação

Object Storage Service:Políticas de retenção (SDK C++)

Última atualização: Sep 22, 2026

As políticas de retenção de dados do Object Storage Service (OSS) utilizam o recurso Write Once Read Many (WORM). Esse recurso armazena dados de forma que não possam ser excluídos nem modificados. Para impedir que qualquer pessoa, incluindo proprietários de recursos, modifique ou exclua objetos em um bucket do OSS por um período determinado, defina uma política de retenção de dados para o bucket. Antes de o período de retenção expirar, só é possível fazer upload de objetos e ler objetos do bucket. Os objetos só poderão ser modificados ou excluídos após o término do período de retenção.

Observações

  • Antes de configurar políticas de retenção, familiarize-se com esse recurso. Para mais informações, consulte Retention policies.

  • Neste tópico, utiliza-se o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Create an OssClient instance.

Criar uma política de retenção de dados

O código a seguir mostra como criar uma política de retenção de dados:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";

      /* Initialize resources such as the network. */
      InitializeSdk();

      ClientConfiguration conf;
      conf.signatureVersion = SignatureVersionType::V4;
      /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
      /* Create a data retention policy and set the object protection period to 1 day. */
      auto outcome = client.InitiateBucketWorm(InitiateBucketWormRequest(BucketName, 1));

      if (outcome.isSuccess()) {      
            std::cout << " InitiateBucketWorm success " << std::endl;
            std::cout << "WormId:" << outcome.result().WormId() << std::endl;
      }
      else {
        /* Handle the exception. */
        std::cout << "InitiateBucketWorm fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
      }

      /* Release resources such as the network. */
      ShutdownSdk();
      return 0;
}

Cancelar uma política de retenção de dados desbloqueada

O exemplo de código a seguir demonstra como cancelar uma política de retenção de dados desbloqueada:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";

      /* Initialize resources such as the network. */
      InitializeSdk();

      ClientConfiguration conf;
      conf.signatureVersion = SignatureVersionType::V4;
      /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
      /* Cancel the unlocked data retention policy. */
      auto outcome = client.AbortBucketWorm(AbortBucketWormRequest(BucketName));

      if (outcome.isSuccess()) {      
        std::cout << " AbortBucketWorm success " << std::endl;
      }
      else {
        /* Handle the exception. */
        std::cout << "AbortBucketWorm fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
      }

      /* Release resources such as the network. */
      ShutdownSdk();
      return 0;
}

Bloquear uma política de retenção de dados

O trecho de código a seguir ilustra como bloquear uma política de retenção de dados:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Enter the data retention policy ID. */
    std::string WormId = "453BA7F15A1C4D599D83EAC0C150****";

      /* Initialize resources such as the network. */
      InitializeSdk();

      ClientConfiguration conf;
      conf.signatureVersion = SignatureVersionType::V4;
      /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
      /* Lock the data retention policy. */
      auto outcome = client.CompleteBucketWorm(CompleteBucketWormRequest(BucketName, WormId));

      if (outcome.isSuccess()) {      
        std::cout << " CompleteBucketWorm success " << std::endl;
      }
      else {
        /* Handle the exception. */
        std::cout << "CompleteBucketWorm fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
      }

      /* Release resources such as the network. */
      ShutdownSdk();
      return 0;
}

Obter uma política de retenção de dados

O código a seguir mostra como consultar uma política de retenção de dados:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
     
      /* Initialize resources such as the network. */
      InitializeSdk();

      ClientConfiguration conf;
      conf.signatureVersion = SignatureVersionType::V4;
      /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
      /* Get the data retention policy. */
      auto outcome = client.GetBucketWorm(GetBucketWormRequest(BucketName));

      if (outcome.isSuccess()) {      
            std::cout << " GetBucketWorm success " << std::endl;
            std::cout << " CreationDate:" << outcome.result().CreationDate() <<
            ",State:" << outcome.result().State() <<
            ",WormId:" << outcome.result().WormId() << std::endl;
      }
      else {
        /* Handle the exception. */
        std::cout << "GetBucketWorm fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
      }

      /* Release resources such as the network. */
      ShutdownSdk();
      return 0;
}

Estender o período de retenção de objetos de uma política bloqueada

O exemplo de código a seguir demonstra como estender o período de retenção de uma política de retenção de dados bloqueada:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Enter the data retention policy ID. */
    std::string WormId = "453BA7F15A1C4D599D83EAC0C150****";

      /* Initialize resources such as the network. */
      InitializeSdk();

      ClientConfiguration conf;
      conf.signatureVersion = SignatureVersionType::V4;
      /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
      /* Extend the object retention period of the locked data retention policy. */
      auto outcome = client.ExtendBucketWormWorm(ExtendBucketWormRequest(BucketName, WormId, 20));

      if (outcome.isSuccess()) {      
        std::cout << " ExtendBucketWormWorm success " << std::endl;
      }
      else {
        /* Handle the exception. */
        std::cout << "ExtendBucketWormWorm fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
      }

      /* Release resources such as the network. */
      ShutdownSdk();
      return 0;
}

Referências

  • Para mais informações sobre a operação de API usada para criar uma política de retenção de dados, consulte InitiateBucketWorm.

  • Para detalhes sobre a operação de API usada para cancelar uma política de retenção de dados desbloqueada, consulte AbortBucketWorm.

  • Para informações sobre a operação de API usada para bloquear uma política de retenção de dados, consulte CompleteBucketWorm.

  • Para saber mais sobre a operação de API usada para consultar uma política de retenção de dados, consulte GetBucketWorm.

  • Para obter detalhes sobre a operação de API usada para estender o período de retenção, consulte ExtendBucketWorm.