Todos los productos
Search
Centro de documentos

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

Última actualización: Sep 22, 2026

La replicación de datos copia automáticamente objetos y operaciones —como la creación, sobrescritura y eliminación de objetos— desde un bucket de origen hacia un bucket de destino. Object Storage Service (OSS) admite cross-region replication (CRR) y same-region replication (SRR).

Notas

  • El código de ejemplo utiliza el ID de región cn-hangzhou, correspondiente a la región China (Hangzhou), y un endpoint público de forma predeterminada. Para acceder a recursos de otros servicios de Alibaba Cloud en la misma región que el bucket, use el endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Una cuenta de Alibaba Cloud tiene los permisos obligatorios de forma predeterminada. Si replica datos como usuario de RAM o mediante credenciales de acceso temporales de Security Token Service (STS), necesita los siguientes permisos:

    • Para habilitar la replicación de datos, requiere el permiso oss:PutBucketReplication.

    • Para habilitar o deshabilitar la función replication time control (RTC), requiere el permiso oss:PutBucketRtc.

    • Para consultar las reglas de replicación de datos, requiere el permiso oss:GetBucketReplication.

    • Para consultar las regiones de destino disponibles para la replicación de datos, requiere el permiso oss:GetBucketReplicationLocation.

    • Para consultar el progreso de una tarea de replicación de datos, requiere el permiso oss:GetBucketReplicationProgress.

    • Para deshabilitar la replicación de datos, requiere el permiso oss:DeleteBucketReplication.

Código de ejemplo

Habilitar la replicación de datos

Importante

Antes de habilitar la replicación de datos, compruebe que tanto el bucket de origen como el de destino se encuentren sin versionado o con el versionado habilitado.

A continuación se muestra el código de ejemplo para habilitar la replicación de datos desde un bucket de origen hacia un bucket de destino, ya sea en la misma región o en una distinta:

<?php

// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

// Use the Alibaba Cloud OSS V2 namespace.
use AlibabaCloud\Oss\V2 as Oss;

// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket" => ['help' => 'The name of the bucket', 'required' => True],
    "target-bucket" => ['help' => 'The name of the target bucket', 'required' => True],
    "target-location" => ['help' => 'The location of the target bucket', 'required' => True],
];

// Create an array of long options required by getopt. Example: ["region:", "endpoint:", ...]
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Retrieve the command-line arguments passed.
$options = getopt("", $longopts);

// Check whether all required parameters are provided. If one is missing, an error message is displayed and the program exits.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help";
        exit(1);
    }
}

// Extract the command-line arguments.
$region = $options["region"];
$bucket = $options["bucket"];
$targetBucket = $options["target-bucket"];
$targetLocation = $options["target-location"];

// Use access credentials stored in environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configuration.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Construct a PutBucketReplicationRequest object.
$request = new Oss\Models\PutBucketReplicationRequest(
    bucket: $bucket,
    replicationConfiguration: new Oss\Models\ReplicationConfiguration(
        rules: array(
            new Oss\Models\ReplicationRule(
                destination: new Oss\Models\ReplicationDestination(
                    bucket: $targetBucket,
                    location: $targetLocation,
                ),
                rtc: new Oss\Models\ReplicationTimeControl(
                    status: 'enabled' // Enable replication time control (RTC).
                )
            )
        )
    )
);

// Execute the request and obtain the result.
$result = $client->putBucketReplication($request);

// Display the status code, request ID, and replication rule ID.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId . PHP_EOL .
    'replication rule id:' . $result->replicationRuleId
);

Consultar las reglas de replicación de datos

El siguiente código consulta las reglas de replicación de datos de un bucket:

<?php

// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket" => ['help' => 'The name of the bucket', 'required' => True],
];

// Construct an array of long options required by getopt.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);

// Traverse all parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
    // If a required parameter is missing, display an error message and exit the program.
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help";
        exit(1);
    }
}

// Extract the region and bucket name from the command-line arguments.
$region = $options["region"];
$bucket = $options["bucket"];

// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Construct a GetBucketReplicationRequest object.
$request = new Oss\Models\GetBucketReplicationRequest(bucket: $bucket);

// Send the request and obtain the result.
$result = $client->getBucketReplication($request);

// Display the status code, request ID, and replication rules.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId . PHP_EOL .
    'replication config:' . var_export($result->replicationConfiguration, true)
);

Habilitar o deshabilitar la función RTC

El siguiente código de ejemplo habilita o deshabilita la función RTC para una regla de CRR:

<?php

// Include the autoload file to load the SDK and dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;

// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket" => ['help' => 'The name of the bucket', 'required' => True],
    "rule-id" => ['help' => 'The replication rule id of the bucket', 'required' => True],
];

// Construct an array of long options required by getopt. A key with a colon at the end expects a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);

// Check whether all required parameters are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help";
        exit(1);
    }
}

// Extract the region, bucket, and replication rule ID.
$region = $options["region"];
$bucket = $options["bucket"];
$ruleId = $options["rule-id"];

// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Construct a PutBucketRtcRequest object.
$request = new Oss\Models\PutBucketRtcRequest(
    bucket: $bucket,
    rtcConfiguration: new Oss\Models\RtcConfiguration(
        rtc: new Oss\Models\ReplicationTimeControl(
            status: 'disabled' // Disable RTC.
        ),
        id: $ruleId // The ID of the replication rule to be modified.
    )
);

$result = $client->putBucketRtc($request);

// Display the status code and request ID.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId
);

Consultar las regiones a las que se pueden replicar los datos

El siguiente código de ejemplo consulta las regiones de destino disponibles para un bucket de origen:

<?php

// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;

// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket" => ['help' => 'The name of the bucket', 'required' => True],
];

// Construct an array of long options required by getopt.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);

// Traverse parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help";
        exit(1);
    }
}

// Extract the region and bucket name from the command-line arguments.
$region = $options["region"];
$bucket = $options["bucket"];

// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a GetBucketReplicationLocationRequest object to query regions to which data can be replicated.
$request = new Oss\Models\GetBucketReplicationLocationRequest(bucket: $bucket);

// Send the request and obtain the result.
$result = $client->getBucketReplicationLocation($request);

// Display the status code, request ID, and available destination regions.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId . PHP_EOL .
    'replication location:' . var_export($result->replicationLocation, true)
);

Consultar el progreso de una tarea de replicación de datos

Nota

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

  • El progreso de una tarea de replicación de datos históricos se expresa como porcentaje. Solo puede consultar este avance en los buckets que tengan habilitada la replicación de datos históricos.

  • El progreso de una tarea de replicación de datos incrementales se expresa como un punto en el tiempo. Los datos almacenados en el bucket de origen antes de ese momento ya se replicaron.

El siguiente código de ejemplo consulta el progreso de replicación de datos para una regla específica:

<?php

// Include the autoload file to load the SDK and dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;

// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket" => ['help' => 'The name of the bucket', 'required' => True],
    "rule-id" => ['help' => 'The replication rule id of the bucket', 'required' => True],
];

// Construct an array of long options required by getopt. A key with a colon at the end expects a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);

// Traverse parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help";
        exit(1);
    }
}

// Extract the region, bucket, and replication rule ID.
$region = $options["region"];
$bucket = $options["bucket"];
$ruleId = $options["rule-id"];

// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Construct a GetBucketReplicationProgressRequest object to query the replication progress for a specific replication rule.
$request = new Oss\Models\GetBucketReplicationProgressRequest(bucket: $bucket, ruleId: $ruleId);

// Send the request and obtain the result.
$result = $client->getBucketReplicationProgress($request);

// Display the status code, request ID, and replication progress details.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId . PHP_EOL .
    'replication progress:' . var_export($result->replicationProgress, true)
);

Deshabilitar la replicación de datos

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

El siguiente código de ejemplo elimina la regla de replicación especificada del bucket indicado:

<?php

// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;

// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket" => ['help' => 'The name of the bucket', 'required' => True],
    "rule-id" => ['help' => 'The replication rule id of the bucket', 'required' => True],
];

// Construct an array of long options required by getopt. A key with a colon at the end expects a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);

// Traverse parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help";
        exit(1);
    }
}

// Extract the region, bucket, and replication rule ID.
$region = $options["region"];
$bucket = $options["bucket"];
$ruleId = $options["rule-id"];

// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Construct a DeleteBucketReplicationRequest object to delete replication rules.
$request = new Oss\Models\DeleteBucketReplicationRequest(
    bucket: $bucket,
    replicationRules: new Oss\Models\ReplicationRules(
        ids: [$ruleId] // The list of IDs of replication rules to be deleted.
    )
);

// Send the request to delete the specified replication rules.
$result = $client->deleteBucketReplication($request);

// Display the status code and request ID.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId
);