O Object Storage Service (OSS) oferece as seguintes classes de armazenamento para atender a diversos cenários, desde dados quentes até dados frios: Standard, Infrequent Access (IA), Archive, Cold Archive e Deep Cold Archive. No OSS, o conteúdo de um objeto não pode ser modificado após sua criação. Para converter a classe de armazenamento de um objeto, use o método Bucket.CopyObject para copiá-lo e definir a nova classe de armazenamento no objeto resultante.
Observações de uso
Este tópico usa 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 obter detalhes sobre regiões e endpoints suportados, consulte Regiões e endpoints.
Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.
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 Configuração do cliente.
Para converter a classe de armazenamento de um objeto, você precisa das permissões
oss:GetObject,oss:PutObjecteoss:RestoreObject. Para mais informações, consulte Conceder uma política personalizada.
Exemplos
Se você converter a classe de armazenamento de um objeto IA, Archive, Cold Archive ou Deep Cold Archive, ou excluir o objeto antes do término da duração mínima de armazenamento, haverá cobrança pelo uso de armazenamento referente ao período inferior ao mínimo exigido. Para mais informações, consulte Como sou cobrado por objetos cuja duração de armazenamento é menor que a duração mínima?
Converter a classe de armazenamento de um objeto de Standard ou IA para Archive, Cold Archive ou Deep Cold Archive
O código de exemplo a seguir mostra como converter a classe de armazenamento de um objeto de Standard ou IA para Archive, Cold Archive ou Deep Cold Archive:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.StorageClass;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// In this example, a bucket and a Standard or IA object are created.
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
String objectName = "exampleobject.txt";
// 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.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a CopyObjectRequest object.
CopyObjectRequest request = new CopyObjectRequest(bucketName, objectName, bucketName, objectName) ;
// Create an ObjectMetadata object.
ObjectMetadata objectMetadata = new ObjectMetadata();
// Convert the storage class of the object to Archive.
objectMetadata.setHeader("x-oss-storage-class", StorageClass.Archive);
// Convert the storage class of the object to Cold Archive.
// objectMetadata.setHeader("x-oss-storage-class", StorageClass.ColdArchive);
// Convert the storage class of the object to Deep Cold Archive.
// objectMetadata.setHeader("x-oss-storage-class", StorageClass.DeepColdArchive);
request.setNewObjectMetadata(objectMetadata);
// Convert the storage class of the object.
CopyObjectResult result = ossClient.copyObject(request);
} 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();
}
}
}
}
Converter a classe de armazenamento de um objeto de Archive para Standard ou IA
O código de exemplo a seguir mostra como converter a classe de armazenamento de um objeto de Archive para Standard ou IA:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.StorageClass;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// In this example, a bucket and an Archive object are created.
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
String objectName = "exampleobject.txt";
// 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.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Query object metadata.
ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);
// Check whether the object whose storage class you want to convert is an Archive object. If the object is an Archive object, you must restore the object before you can convert the storage class.
StorageClass storageClass = objectMetadata.getObjectStorageClass();
System.out.println("storage type:" + storageClass);
if (storageClass == StorageClass.Archive) {
// Restore the object.
ossClient.restoreObject(bucketName, objectName);
// Wait until the object is restored.
do {
Thread.sleep(1000);
objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);
} while (!objectMetadata.isRestoreCompleted());
}
// Create a CopyObjectRequest object.
CopyObjectRequest request = new CopyObjectRequest(bucketName, objectName, bucketName, objectName) ;
// Create an ObjectMetadata object.
objectMetadata = new ObjectMetadata();
// Convert the storage class of the object to IA.
objectMetadata.setHeader("x-oss-storage-class", StorageClass.IA);
// Convert the storage class of the object to Standard.
// objectMetadata.setHeader("x-oss-storage-class", StorageClass.Standard);
request.setNewObjectMetadata(objectMetadata);
// Convert the storage class of the object.
CopyObjectResult result = ossClient.copyObject(request);
} 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();
}
}
}
}
Referências
Para obter o código de exemplo completo sobre conversão de classes de armazenamento, visite o GitHub.
Para obter detalhes sobre a operação de API usada para converter a classe de armazenamento de um objeto, consulte CopyObject.