Todos os produtos
Search
Central de documentação

Object Storage Service:Replicação de dados com o OSS SDK for Go 2.0

Última atualização: Sep 22, 2026

Os recursos de replicação de dados permitem sincronizar automaticamente objetos e as operações realizadas neles — como criação, substituição e exclusão — de um bucket de origem (source) para um bucket de destino. O OSS oferece dois recursos de replicação de dados: replicação entre regiões (CRR) e replicação na mesma região (SRR).

Observações

  • O código de exemplo neste tópico utiliza o ID de região cn-hangzhou da região China (Hangzhou). Por padrão, o endpoint público é usado para acessar recursos em um bucket. Para acessar recursos no bucket por meio de outros serviços Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre as regiões e endpoints compatíveis com o Object Storage Service (OSS), consulte OSS regions and endpoints.

  • Neste tópico, as credenciais de acesso são obtidas a partir de variáveis de ambiente. Para mais informações sobre como configure credenciais de acesso, consulte Configure access credentials (Go SDK V1).

  • Por padrão, uma conta Alibaba Cloud já possui permissões relacionadas à replicação de dados. Para replicar dados como usuário RAM ou com credenciais temporárias fornecidas pelo Security Token Service (STS), você precisa das permissões adequadas. Por exemplo:

    • A permissão oss:PutBucketReplication é necessária para ativar a replicação de dados.

    • A permissão oss:PutBucketRtc é necessária para ativar e desativar o recurso de controle de tempo de replicação (RTC).

    • A permissão oss:GetBucketReplication é necessária para consultar regras de replicação de dados.

    • A permissão oss:GetBucketReplicationLocation é necessária para consultar as regiões de destino disponíveis.

    • A permissão oss:GetBucketReplicationProgress é necessária para consultar o progresso de uma tarefa de replicação de dados.

    • A permissão oss:DeleteBucketReplication é necessária para desativar a replicação de dados.

Código de exemplo

Ative a replicação de dados

Importante

Antes de ativar a replicação de dados, verifique se o bucket de origem e o bucket de destino estão sem versionamento ou com versionamento habilitado.

O código a seguir mostra como ativar a replicação de dados. Os buckets de origem e destino podem estar na mesma região ou em regiões diferentes.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	var (
		targetBucket   = "target bucket name" // Name of the destination bucket.
		targetLocation = "oss-cn-beijing"     // Region in which the destination bucket is located.
	)

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to enable data replication for the bucket.
	request := &oss.PutBucketReplicationRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		ReplicationConfiguration: &oss.ReplicationConfiguration{
			Rules: []oss.ReplicationRule{
				{
					RTC: &oss.ReplicationTimeControl{
						Status: oss.Ptr("enabled"), // Enable the RTC feature.
					},
					Destination: &oss.ReplicationDestination{
						Bucket:       oss.Ptr(targetBucket),   // Name of the destination bucket.
						Location:     oss.Ptr(targetLocation), // Region in which the destination bucket is located.
						TransferType: oss.TransferTypeOssAcc,  // Type of transfer.
					},
					HistoricalObjectReplication: oss.HistoricalObjectReplicationEnabled, // Enable the historical data replication feature.
				},
			},
		},
	}

	// Enable data replication.
	result, err := client.PutBucketReplication(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket replication %v", err)
	}

	// Display the result.
	log.Printf("put bucket replication result:%#v\n", result)
}

Consultar regras de replicação de dados

O código a seguir mostra como consultar as regras de replicação de dados de um bucket.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the data replication rules of the bucket.
	request := &oss.GetBucketReplicationRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Perform the query operation.
	getResult, err := client.GetBucketReplication(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket replication %v", err)
	}

	// Display the result.
	log.Printf("get bucket replication result:%#v\n", getResult)
}

Ative ou desative o recurso RTC

O código a seguir mostra como ativar ou desativar o recurso RTC para uma regra de CRR.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	var (
		ruleId = "replication id"
	)

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to enable or disable the RTC feature.
	request := &oss.PutBucketRtcRequest{
		Bucket: oss.Ptr(bucketName),
		RtcConfiguration: &oss.RtcConfiguration{
			RTC: &oss.ReplicationTimeControl{
				Status: oss.Ptr("enabled"),
			},
			ID: oss.Ptr(ruleId), // Specify the ID of the replication rule.
		},
	}

	// Perform the operation to enable or disable the RTC feature.
	result, err := client.PutBucketRtc(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket rtc %v", err)
	}

	// Display the result.
	log.Printf("put bucket rtc result:%#v\n", result)
}

Consultar as regiões para as quais os dados podem ser replicados

O código a seguir mostra como consultar as regiões para as quais os dados de um bucket podem ser replicados.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the regions to which data in the source bucket can be replicated.
	request := &oss.GetBucketReplicationLocationRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Perform the query operation.
	result, err := client.GetBucketReplicationLocation(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket replication location %v", err)
	}

	// Display information about the regions.
	for _, location := range result.ReplicationLocation.Locations {
		log.Printf("Bucket Replication Location: %s", location)
	}

	// Display the region for which the RTC feature can be enabled.
	for _, rtcLocation := range result.ReplicationLocation.LocationRTCConstraint.Locations {
		log.Printf("Bucket Replication Location RTC Location: %s", rtcLocation)
	}
}

Consultar o progresso de uma tarefa de replicação de dados

Nota

É possível consultar o progresso de tarefas de replicação de dados históricos e de tarefas de replicação de dados incrementais.

  • O progresso das tarefas de replicação de dados históricos é expresso em porcentagem. Essa consulta está disponível apenas para buckets com replicação de dados históricos ativada.

  • O progresso das tarefas de replicação de dados incrementais é expresso como um ponto no tempo. Os dados armazenados no bucket de origem antes desse ponto no tempo já foram replicados.

O código a seguir mostra como consultar o progresso da tarefa de replicação de dados com um ID de regra de replicação específico em um bucket.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Specify the ID of the replication rule.
	var ruleId = "replication id"

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the progress of the data replication task.
	request := &oss.GetBucketReplicationProgressRequest{
		Bucket: oss.Ptr(bucketName),
		RuleId: oss.Ptr(ruleId), // Specify the ID of the replication rule.
	}

	// Perform the query operation.
	result, err := client.GetBucketReplicationProgress(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket replication progress %v", err)
	}

	// Display the progress of the data replication task.
	for _, repProgressRule := range result.ReplicationProgress.Rules {
		log.Printf("Rule Id: %s", repProgressRule.ID)
		log.Printf("Status: %s", repProgressRule.Status)
		log.Printf("Replication Progress Rule Destination Bucket: %s", *repProgressRule.Destination.Bucket)
		log.Printf("Replication Progress Rule Destination Location: %s", *repProgressRule.Destination.Location)
		log.Printf("Replication Progress Rule Destination TransferType: %v", repProgressRule.Destination.TransferType)
		log.Printf("Replication Progress Rule Historical Object Replication: %s", *repProgressRule.HistoricalObjectReplication)
	}
}

Desativar a replicação de dados

Para desativar a replicação de dados de um bucket, exclua a regra de replicação configurada para o bucket de origem especificado.

O código a seguir mostra como excluir a regra de replicação com um ID específico.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Specify the ID of the replication rule.
	var ruleId = "replication id"

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the data replication rule configured for the bucket.
	request := &oss.DeleteBucketReplicationRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		ReplicationRules: &oss.ReplicationRules{
			IDs: []string{ruleId}, // List of replication rule IDs.
		},
	}

	// Perform the operation to delete the data replication rule.
	result, err := client.DeleteBucketReplication(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket replication %v", err)
	}

	// Display the result.
	log.Printf("delete bucket replication result:%#v\n", result)
}

Referências

  • Para mais informações sobre a operação de API usada para ativar a replicação de dados, consulte PutBucketReplication.

  • Para detalhes sobre a operação de API para ativar ou desativar o recurso RTC em regras de CRR existentes, consulte PutBucketRTC.

  • Para saber mais sobre a operação de API para consultar regras de replicação de dados, consulte GetBucketReplication.

  • Para informações sobre a operação de API para consultar as regiões para as quais os dados podem ser replicados, consulte GetBucketReplicationLocation.

  • Para mais informações sobre a operação de API para consultar o progresso de uma tarefa de replicação de dados, consulte GetBucketReplicationProgress.

  • Para detalhes sobre a operação de API para desativar a replicação de dados, consulte DeleteBucketReplication.