O armazenamento com redundância de zona (ZRS) do OSS oferece durabilidade de dados de 99,9999999999% (12 noves). Em regiões multizona, o OSS distribui cópias redundantes entre as zonas de disponibilidade da mesma região. Isso garante acesso contínuo aos dados durante falhas de zona e possibilita a recuperação de desastres no nível de data center.
Cenários
O ZRS proporciona recuperação de desastres no nível de data center. Caso um data center fique indisponível devido a interrupções de rede, falhas de energia ou desastres, o OSS mantém o serviço fortemente consistente. O failover ocorre automaticamente, sem interrupções e sem perda de dados (RPO = 0).
Observações
As regiões suportadas, a durabilidade dos dados e a disponibilidade do serviço estão listadas em Redundância de armazenamento.
O ZRS gera custos de armazenamento mais altos que o armazenamento localmente redundante. Para mais informações, consulte Preços do Object Storage Service.
Não é possível desativar o ZRS após ativá-lo para um bucket.
Procedimento
Usar o console do OSS
Faça login no console do OSS.
No painel de navegação à esquerda, clique em Buckets e, em seguida, clique em Create Bucket.
-
No painel Create Bucket, defina Redundancy Type como ZRS (Recommended) e configure os demais parâmetros.
Os outros parâmetros são descritos em Criar um bucket.
Usar SDKs do Alibaba Cloud
Os exemplos a seguir criam um bucket ZRS usando SDKs populares. Outros SDKs estão listados em SDKs.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
public class Demo {
public static void main(String[] args) throws Exception {
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this 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 bucket name.
String bucketName = "examplebucket";
// Specify the resource group ID. If you do not specify a resource group ID, the bucket is added to the default resource group.
//String rsId = "rg-aek27tc****";
// Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// After an OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a bucket and enable the hierarchical namespace feature.
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName).withHnsStatus(HnsStatus.Enabled);
// If you want to specify the storage class, ACL, and data redundancy type when you create a bucket, see the following code.
// The following code provides an example of how to set the storage class to Standard.
createBucketRequest.setStorageClass(StorageClass.Standard);
// The default data redundancy type is LRS, which is specified as DataRedundancyType.LRS. If you want to set the data redundancy type to ZRS, set the value to DataRedundancyType.ZRS.
createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS);
// Set the ACL of the bucket to public-read. The default ACL is private.
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
// When you create a bucket in a region that supports resource groups, you can assign the bucket to a resource group.
//createBucketRequest.setResourceGroupId(rsId);
// Create the bucket.
ossClient.createBucket(createBucketRequest);
} 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();
}
}
}
}
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourBucketName',
});
// Create the bucket.
async function putBucket() {
try {
const options = {
storageClass: 'Standard', // By default, the storage class of a bucket is Standard. To set the storage class of the bucket to Archive, set storageClass to Archive.
acl: 'private', // By default, the access control list (ACL) of a bucket is private. To set the ACL of the bucket to public read, set acl to public-read.
dataRedundancyType: 'LRS' // By default, the redundancy type of a bucket is locally redundant storage (LRS). To set the redundancy type of the bucket to zone-redundant storage (ZRS), set dataRedundancyType to ZRS.
}
// Specify the name of the bucket.
const result = await client.putBucket('examplebucket', options);
console.log(result);
} catch (err) {
console.log(err);
}
}
putBucket();
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put bucket sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
args = parser.parse_args() # Parse command-line arguments.
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If the endpoint argument is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client using the configured information.
client = oss.Client(cfg)
# Send a request to create a bucket. The storage class is Standard.
result = client.put_bucket(oss.PutBucketRequest(
bucket=args.bucket,
create_bucket_configuration=oss.CreateBucketConfiguration(
storage_class='Standard',
data_redundancy_type='ZRS'
)
))
# Print the status code and request ID to verify whether the request succeeded.
print(f'status code: {result.status_code},'
f' request id: {result.request_id}'
)
if __name__ == "__main__":
main() # The entry point of the script. The main function is called when the file is run directly.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// Create a bucket.
try
{
var request = new CreateBucketRequest(bucketName);
// Set the access control list (ACL) to public-read. The default ACL is private.
request.ACL = CannedAccessControlList.PublicRead;
// Set the data disaster recovery type to zone-redundant storage.
request.DataRedundancyType = DataRedundancyType.ZRS;
client.CreateBucket(request);
Console.WriteLine("Create bucket succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Create bucket failed. {0}", ex.Message);
}
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 command-line arguments.
var (
region string // The region where the bucket is located.
bucketName string // The name of the bucket.
)
// Initialize command-line argument parsing.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse command-line arguments.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Configure the OSS client.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). // Use environment variables to provide access credentials.
WithRegion(region) // Set the region.
// Create an OSS client instance.
client := oss.NewClient(cfg)
// Build a request to create a bucket.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr(bucketName), // Set the bucket name.
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
DataRedundancyType: oss.DataRedundancyZRS, // Set the data redundancy type to ZRS (Zone-Redundant Storage).
},
}
// Send the request to create the bucket.
result, err := client.PutBucket(context.TODO(), request)
if err != nil {
log.Fatalf("failed to create bucket: %v", err) // Handle the error and stop the program.
}
// Print the result of creating the bucket.
log.Printf("put bucket result: %#v\n", result)
}
Usar o ossutil
Para criar um bucket ZRS com o ossutil, execute o comando put-bucket.
Usar uma API REST
Para requisitos personalizados, chame a API REST diretamente. É necessário calcular a assinatura manualmente. Consulte PutBucket.