La réplication des données copie automatiquement les objets et les opérations associées, telles que la création, l'écrasement et la suppression, d'un bucket source vers un bucket de destination. Object Storage Service (OSS) prend en charge la réplication inter-régions (CRR) et la réplication intra-région (SRR).
Notes d'utilisation
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour obtenir la liste des régions et des points de terminaison pris en charge, consultez Régions et points de terminaison.
Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour plus d'informations, consultez Configuration des identifiants d'accès.
Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, comme l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configuration du client.
Pour activer la réplication des données, vous devez disposer de l'autorisation
oss:PutBucketReplication. Pour interroger les règles de réplication des données, vous devez disposer de l'autorisationoss:GetBucketReplication. Pour consulter les régions vers lesquelles les données peuvent être répliquées, vous devez disposer de l'autorisationoss:GetBucketReplicationLocation. Pour suivre la progression d'une tâche de réplication des données, vous devez disposer de l'autorisationoss:GetBucketReplicationProgress. Pour désactiver la réplication des données, vous devez disposer de l'autorisationoss:DeleteBucketReplication. Pour plus d'informations, consultez Accorder une politique personnalisée.
Activer la réplication des données
Avant d'activer la réplication des données, assurez-vous que le bucket source et le bucket de destination ne sont pas versionnés ou que le versioning est activé.
L'exemple de code suivant montre comment configurer une règle de réplication des données :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.AddBucketReplicationRequest;
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 destination bucket to which you want to replicate the data.
String targetBucketName = "yourTargetBucketName";
// Specify the region in which the destination bucket is located.
// If you want to enable CRR, the source and destination buckets must be located in different regions. If you want to enable SRR, the source and destination buckets must be located in the same region.
String targetBucketLocation = "yourTargetBucketLocation";
// 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 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 {
AddBucketReplicationRequest request = new AddBucketReplicationRequest(bucketName);
request.setTargetBucketName(targetBucketName);
request.setTargetBucketLocation(targetBucketLocation);
// Specify whether to replicate historical data. By default, historical data is replicated. In this example, historical data is not replicated.
request.setEnableHistoricalObjectReplication(false);
// Specify the name of the role that you want to authorize OSS to use for data replication. If you want to use SSE-KMS to encrypt the objects that are replicated to the destination bucket, you must specify a role.
//request.setSyncRole("yourRole");
// Specify whether to replicate the objects that are encrypted by using SSE-KMS.
//request.setSseKmsEncryptedObjectsStatus("Enabled");
// Specify the customer master key (CMK) ID used in SSE-KMS. If Status is set to Enabled, you must specify a key ID.
//request.setReplicaKmsKeyID("3542abdd-5821-4fb5-a425-90adca***");
//List prefixes = new ArrayList();
//prefixes.add("image/");
//prefixes.add("video");
//prefixes.add("a");
//prefixes.add("A");
// Specify the prefixes that are contained in the names of the objects that you want to replicate. After you specify the prefixes, only objects whose names contain the prefixes are replicated to the destination bucket.
//request.setObjectPrefixList(prefixes);
//List actions = new ArrayList();
//actions.add(AddBucketReplicationRequest.ReplicationAction.PUT);
// Replicate the object creation and update operations to the destination bucket.
//request.setReplicationActionList(actions);
ossClient.addBucketReplication(request);
} 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 (ClientException 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();
}
}
}
}
Interroger les règles de réplication des données
L'exemple de code suivant montre comment interroger les règles de réplication des données d'un bucket :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ReplicationRule;
import java.util.List;
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 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 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 {
// Query the data replication rules.
List<ReplicationRule> rules = ossClient.getBucketReplication(bucketName);
for (ReplicationRule rule : rules) {
System.out.println(rule.getReplicationRuleID());
System.out.println(rule.getTargetBucketLocation());
System.out.println(rule.getTargetBucketName());
}
} 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 (ClientException 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();
}
}
}
}
Interroger les régions vers lesquelles les données peuvent être répliquées
L'exemple de code suivant montre comment interroger les régions vers lesquelles les données peuvent être répliquées :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import java.util.List;
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 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 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 {
// Query the regions of buckets to which data can be replicated.
List<String> locations = ossClient.getBucketReplicationLocation(bucketName);
for (String loc : locations) {
System.out.println(loc);
}
} 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 (ClientException 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();
}
}
}
}
Interroger la progression d'une tâche de réplication des données
Vous pouvez consulter la progression des tâches de réplication des données historiques et incrémentielles.
La progression des tâches de réplication des données historiques est exprimée en pourcentage. Vous ne pouvez interroger la progression des tâches de réplication des données historiques que pour les buckets pour lesquels la réplication des données historiques est activée.
La progression des tâches de réplication des données incrémentielles est exprimée sous forme d'un instant précis. Les données stockées dans le bucket source avant cet instant sont répliquées.
L'exemple de code suivant montre comment interroger la progression d'une tâche de réplication des données :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.BucketReplicationProgress;
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 ID of the data replication rule.
String ruleId = "yourRuleId";
// 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 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 {
BucketReplicationProgress process = ossClient.getBucketReplicationProgress(bucketName, ruleId);
System.out.println(process.getReplicationRuleID());
System.out.println(process.isEnableHistoricalObjectReplication());
// Query the progress of the data replication task.
System.out.println(process.getHistoricalObjectProgress());
// Query the progress of the real-time data replication task.
System.out.println(process.getNewObjectProgress());
} 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 (ClientException 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();
}
}
}
}
Désactiver la réplication des données
L'exemple de code suivant montre comment désactiver la réplication des données :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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";
String ruleId = "yourRuleId";
// 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 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 {
// Disable data replication. After data replication is disabled, the objects that are replicated to the destination bucket still exist. However, all changes to the objects in the source bucket are no longer replicated to the destination bucket.
ossClient.deleteBucketReplication(bucketName, ruleId);
} 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 (ClientException 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();
}
}
}
}
Références
Pour obtenir l'exemple de code complet relatif à la réplication des données, visitez GitHub.
Pour plus d'informations sur l'opération API permettant d'activer la réplication des données, consultez PutBucketReplication.
Pour plus d'informations sur l'opération API permettant d'interroger les règles de réplication des données, consultez GetBucketReplication.
Pour plus d'informations sur l'opération API permettant d'interroger les régions vers lesquelles les données peuvent être répliquées, consultez GetBucketReplicationLocation.
Pour plus d'informations sur l'opération API permettant d'interroger la progression d'une tâche de réplication des données, consultez GetBucketReplicationProgress.
Pour plus d'informations sur l'opération API permettant de désactiver la réplication des données, consultez DeleteBucketReplication.