Ao baixar um objeto maior que 5 GB do Object Storage Service (OSS) para um computador local, falhas podem ocorrer devido a interrupções de rede ou travamentos do programa. Se o download falhar após várias tentativas, utilize o download retomável. Esse recurso permite dividir o objeto em várias partes e baixá-las em paralelo para acelerar a transferência. O progresso fica registrado em um arquivo de checkpoint. Caso uma parte falhe, o próximo download continua a partir da posição salva nesse arquivo. Após a conclusão, todas as partes são combinadas no 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 serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
As credenciais de acesso neste exemplo são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
O exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).
O download retomável exige a permissão
oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.O progresso do download é gravado em um arquivo de checkpoint. Se houver falha em alguma parte, a próxima tentativa inicia a partir da posição registrada. O arquivo de checkpoint é excluído automaticamente ao final do download retomável.
O OSS SDK for Go registra o progresso no arquivo de checkpoint. Verifique se você tem permissão de escrita nesse arquivo.
Não modifique a soma de verificação contida no arquivo de checkpoint. Se o arquivo estiver corrompido, será necessário baixar todas as partes novamente.
Caso o ETag do objeto seja inconsistente ou partes sejam perdidas ou modificadas durante a transferência, baixe o objeto novamente.
Exemplos
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// 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. Specify your actual endpoint.
// 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. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket. Example: examplebucket.
bucket, err := client.Bucket("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify the path of the local file, the downloaded object is saved to the path of the project to which the sample program belongs.
// Set the size of each part that you want to download to 100 KB (100 x 1024) and set the number of concurrent download parts to 3.
// oss.Checkpoint(true, "") Specify that resumable download is enabled. By default, the checkpoint file and the downloaded object are stored in the same directory and share the same name. However, the extension of the checkpoint file is .temp. You can also use oss.Checkpoint(true, "your-cp-file.temp") to specify the name of the checkpoint file.
err = bucket.DownloadFile("file.zip", "D:\\file.zip", 100*1024, oss.Routines(3), oss.Checkpoint(true, ""))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}