O baixe de objetos grandes pode falhar devido a instabilidade na rede ou outras exceções. Em alguns casos, o erro persiste mesmo após várias tentativas. Para resolver esse problema, o Object Storage Service (OSS) oferece o recurso de baixe retomável. Nesse modo, o OSS divide o objeto em várias partes e baixa cada uma separadamente. Após baixar todas as partes, o OSS as combina para formar o objeto completo.
Observações de uso
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros services da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints compatíveis, consulte Regions and endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações, consulte 配置访问凭证.
Este tópico demonstra como crie 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 Client configuration.
Para usar o baixe retomável, você precisa da permissão
oss:GetObject. Para mais informações, consulte Grant a custom policy.
Ajuste de desempenho
A velocidade do baixe retomável depende do tamanho da parte, do número de tarefas simultâneas e do tamanho do pool de conexões do cliente OSS. Configure os seguintes parâmetros com base no tamanho do objeto e nos recursos do cliente:
Tamanho da parte: defina
PartSizecom um valor entre 1 MB e 10 MB. Quanto maior o objeto, maior pode ser o tamanho da parte. Aumentar o tamanho da parte de 1 MB para 10 MB melhora a velocidade de baixe em aproximadamente 80%, tornando este o parâmetro mais eficaz para ajuste.Número de tarefas simultâneas: defina
TaskNumcom um valor entre 10 e 50. Se você especifique um valor superior a 50, a velocidade de baixe ficará limitada pela largura de banda da rede, pelos recursos de CPU e memória do cliente e pela cota de largura de banda da rede interna da VPC. Nesse cenário, valores maiores proporcionam apenas melhorias limitadas.Tamanho do pool de conexões: chame o método
setMaxConnectionsCountdeClientBuilderConfigurationpara definir o tamanho do pool de conexões com um valor igual ou superior ao número de tarefas simultâneas. Caso contrário, as tarefas simultâneas aguardarão conexões disponíveis.
Exemplos
O código de exemplo a seguir mostra como execute um baixe retomável:
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
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();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
String objectName = "exampledir/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 associated 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 {
// Perform resumable download in which 10 parts can be concurrently downloaded.
DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, objectName);
// Specify the full path to which you want to download the object. Example: D:\\localpath\\examplefile.txt.
downloadFileRequest.setDownloadFile("D:\\localpath\\examplefile.txt");
// Specify the part size. Unit: bytes. Valid values: 100 KB to 5 GB. The default part size is 100 KB.
downloadFileRequest.setPartSize(1 * 1024 * 1024);
// Specify the number of concurrent threads for the resumable download task. Default value: 1.
downloadFileRequest.setTaskNum(10);
// Specify whether to enable resumable download. By default, resumable download is disabled.
downloadFileRequest.setEnableCheckpoint(true);
// Specify the full path of the checkpoint file. Example: D:\\localpath\\examplefile.txt.dcp.
// The checkpoint file is generated when the download is interrupted. If you want to resume the download task, you must specify the full path of the checkpoint file. After the object is downloaded, the checkpoint file is deleted.
//downloadFileRequest.setCheckpointFile("D:\\localpath\\examplefile.txt.dcp");
// Download the object.
DownloadFileResult downloadRes = ossClient.downloadFile(downloadFileRequest);
// After the object is downloaded, the object metadata is returned.
ObjectMetadata objectMetadata = downloadRes.getObjectMetadata();
System.out.println(objectMetadata.getETag());
System.out.println(objectMetadata.getLastModified());
System.out.println(objectMetadata.getUserMetadata().get("meta"));
} 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 (Throwable 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();
}
}
}
}