Todos los productos
Search
Centro de documentos

Object Storage Service:Replicación de datos con OSS SDK for Go 2.0

Última actualización: Sep 22, 2026

Las funciones de replicación de datos permiten sincronizar automáticamente los objetos y las operaciones que se realizan sobre ellos, como la creación, sobrescritura y eliminación de objetos desde un bucket de origen hacia un bucket de destino. OSS ofrece dos funciones de replicación de datos: cross-region replication (CRR) y same-region replication (SRR).

Notas

  • El código de ejemplo de este tema utiliza el identificador de región cn-hangzhou, correspondiente a China (Hangzhou). De forma predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si necesita acceder a dichos recursos mediante otros servicios de Alibaba Cloud ubicados en la misma región que el bucket, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles con Object Storage Service (OSS), consulte OSS regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen a partir de variables de entorno. Para conocer cómo configurar las credenciales de acceso, consulte Configure access credentials (Go SDK V1).

  • De forma predeterminada, una cuenta de Alibaba Cloud tiene los permisos relacionados con la replicación de datos. Si desea replicar datos como usuario de RAM o mediante credenciales de acceso temporales proporcionadas por Security Token Service (STS), es obligatorio disponer de los permisos necesarios. Por ejemplo:

    • El permiso oss:PutBucketReplication es obligatorio para habilitar la replicación de datos.

    • El permiso oss:PutBucketRtc es obligatorio para habilitar y deshabilitar la función de control del tiempo de replicación (RTC).

    • El permiso oss:GetBucketReplication es obligatorio para consultar las reglas de replicación de datos.

    • El permiso oss:GetBucketReplicationLocation es obligatorio para consultar las regiones de destino disponibles.

    • El permiso oss:GetBucketReplicationProgress es obligatorio para consultar el progreso de una tarea de replicación de datos.

    • El permiso oss:DeleteBucketReplication es obligatorio para deshabilitar la replicación de datos.

Código de ejemplo

Habilitar la replicación de datos

Importante

Antes de habilitar la replicación de datos, compruebe que el bucket de origen y el bucket de destino no tengan habilitado el control de versiones o bien lo tengan activado.

A continuación se muestra un ejemplo de cómo habilitar la replicación de datos. Los buckets de origen y de destino pueden encontrarse en la misma región o en regiones distintas.

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 las reglas de replicación de datos

A continuación se muestra un ejemplo de cómo consultar las reglas de replicación de datos de un 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)
}

Habilitar o deshabilitar la función RTC

A continuación se muestra un ejemplo de cómo habilitar o deshabilitar la función RTC para una regla 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 las regiones a las que se pueden replicar los datos

A continuación se muestra un ejemplo de cómo consultar las regiones a las que se pueden replicar los datos desde un 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 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 el progreso de una tarea de replicación de datos

Nota

Es posible consultar el progreso de las tareas de replicación de datos históricos y de las tareas de replicación de datos incrementales.

  • El progreso de las tareas de replicación de datos históricos se expresa como un porcentaje. Este valor solo se puede consultar en los buckets que tienen habilitada la replicación de datos históricos.

  • El progreso de las tareas de replicación de datos incrementales se expresa como un momento específico. Los datos almacenados en el bucket de origen antes de ese momento ya se han replicado.

A continuación se muestra un ejemplo de cómo consultar el progreso de la tarea de replicación de datos asociada a un identificador de regla específico dentro de un 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)
	}
}

Deshabilitar la replicación de datos

Para deshabilitar la replicación de datos de un bucket, elimine la regla de replicación configurada en el bucket de origen especificado.

A continuación se muestra un ejemplo de cómo eliminar una regla de replicación con un identificador determinado.

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)
}

Referencias

  • Para obtener más información sobre la operación de API que permite habilitar la replicación de datos, consulte PutBucketReplication.

  • Si desea conocer más detalles sobre la operación de API que permite habilitar o deshabilitar la función RTC en reglas de CRR existentes, consulte PutBucketRTC.

  • Respecto a la operación de API para consultar las reglas de replicación de datos, consulte GetBucketReplication.

  • En cuanto a la operación de API para consultar las regiones a las que se pueden replicar los datos, consulte GetBucketReplicationLocation.

  • También puede revisar la operación de API para consultar el progreso de una tarea de replicación de datos en GetBucketReplicationProgress.

  • Finalmente, para obtener más información sobre la operación de API que permite deshabilitar la replicación de datos, consulte DeleteBucketReplication.