Bucket adalah wadah dasar dalam Object Storage Service (OSS) yang menyimpan file Anda. Bucket memiliki kapasitas tak terbatas dan bersifat elastis.
Konfigurasi dasar
Berikut adalah pengaturan inti untuk bucket. Pengaturan ini tidak dapat diubah setelah bucket dibuat.
Nama bucket: Nama bucket harus unik secara global. Disarankan memberi nama bucket berdasarkan departemen atau layanan Anda agar mudah diidentifikasi dan dikelola. Contoh:
hr-documents.Region: Region menentukan lokasi fisik data Anda. Pilih region berdasarkan prioritas berikut:
Kepatuhan: Pilih region yang memenuhi persyaratan regulasi Anda.
Kinerja: Untuk mengurangi latensi jaringan, pilih region yang paling dekat dengan pengguna target Anda. Jika Anda mengakses data dari produk Alibaba Cloud lainnya, seperti Instance ECS, pilih region yang sama. Hal ini memungkinkan Anda menggunakan jaringan internal secara gratis dan mengurangi latensi lintas region.
Dukungan fitur: Pastikan region tersebut mendukung fitur yang Anda butuhkan. Untuk informasi selengkapnya, lihat Catatan rilis.
Biaya: Setelah memenuhi kondisi di atas, pilih region dengan harga lebih rendah.
Jika Anda hanya menentukan nama bucket dan region, pengaturan default berikut akan digunakan: penyimpanan Standard, penyimpanan redundan zona, akses privat, dan Blokir Akses Publik diaktifkan.
Konsol
Pada halaman Bucket di Konsol OSS, klik Create Bucket.
Pada panel Create Bucket, atur Bucket Name dan Region, lalu klik Create.
ossutil
Anda dapat menggunakan antarmuka baris perintah (CLI) ossutil untuk membuat bucket. Untuk informasi selengkapnya tentang cara menginstal ossutil, lihat Instal ossutil.
Konfigurasikan region bucket.
ossutil configTekan Enter untuk melewati item konfigurasi awal hingga muncul prompt konfigurasi region:
Please enter Region [cn-hangzhou]:Masukkan ID wilayah tujuan, misalnya
cn-beijing, lalu tekan Enter. Atau, tekan Enter untuk menggunakan region defaultcn-hangzhou. Anda dapat menemukan ID region di daftar region OSS.Buat bucket bernama examplebucket.
ossutil mb oss://examplebucketVerifikasi bahwa bucket telah dibuat.
ossutil ls
Untuk informasi selengkapnya tentang perintah ini, lihat mb (buat bucket).
SDK
Contoh kode berikut menunjukkan cara membuat bucket menggunakan SDK umum. Untuk contoh kode SDK lainnya, lihat Pengenalan SDK.
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 in the China (Hangzhou) region, set the 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 belongs to the default resource group.
//String rsId = "rg-aek27tc****";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer in use, 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);
// To specify the storage class, ACL, and data redundancy type when you create the bucket, see the following code.
// This example shows how to set the storage class of the bucket to Standard.
createBucketRequest.setStorageClass(StorageClass.Standard);
// The default data redundancy type is LRS, which is DataRedundancyType.LRS.
createBucketRequest.setDataRedundancyType(DataRedundancyType.LRS);
// 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 configure a resource group for the bucket.
//createBucketRequest.setResourceGroupId(rsId);
ossClient.createBucket(createBucketRequest);
// 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();
}
}
}
}import argparse
import alibabacloud_oss_v2 as oss
# Create a command line argument parser.
parser = argparse.ArgumentParser(description="put bucket sample")
# Specify the required command line parameter --region, which specifies the region in which the bucket is located.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the required command line parameter --bucket, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the optional command line parameter --endpoint, which specifies the endpoint that other services can use to access OSS.
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 parameters.
# Load access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located.
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance.
client = oss.Client(cfg)
# Execute the request to create a bucket and set its storage class to Standard.
result = client.put_bucket(oss.PutBucketRequest(
bucket=args.bucket,
create_bucket_configuration=oss.CreateBucketConfiguration(
storage_class='Standard'
)
))
# Output the HTTP status code in the response and the request ID used to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
)
if __name__ == "__main__":
main() # Entry point of the script. The main function is invoked when the file is run directly.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"
)
// Specify the global variables.
var (
region string // The region.
bucketName string // The name of the bucket.
)
// Specify the init function used to initialize command line parameters.
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 parameters.
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")
}
// 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)
request := &oss.PutBucketRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
}
// Send a request to create a bucket.
result, err := client.PutBucket(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket %v", err)
}
// Display the result of the bucket creation.
log.Printf("put bucket result:%#v\n", result)
}
<?php
// Automaticically load objects and dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify command line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region parameter is required. Example: oss-cn-hangzhou.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket is required.
];
// Generate a list of long options for parsing command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));
// Parse command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters have been configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
exit(1);
}
}
// Retrieve the values of the command line parameters.
$region = $options["region"]; // Region in which the bucket is located.
$bucket = $options["bucket"]; // Name of the bucket.
// Load the credential information (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a request to initiate bucket creation.
$request = new Oss\Models\PutBucketRequest($bucket);
// Call the putBucket method.
$result = $client->putBucket($request);
// Output the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // HTTP status code.
'request id:' . $result->requestId // Unique ID of the request.
);
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);
}const OSS = require('ali-oss');
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is 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 the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'yourBucketName',
});
// Create a bucket.
async function putBucket() {
try {
const options = {
storageClass: 'Standard', // The default storage class of the bucket is Standard. To set the storage class to Archive, replace Standard with Archive.
acl: 'private', // The default access control list (ACL) of the bucket is private. To set the ACL to public-read, replace private with public-read.
dataRedundancyType: 'LRS' // The default data disaster recovery type of the bucket is locally redundant storage (LRS). To set the data disaster recovery type to zone-redundant storage (ZRS), replace LRS with ZRS.
}
// Specify the bucket name.
const result = await client.putBucket('examplebucket', options);
console.log(result);
} catch (err) {
console.log(err);
}
}
putBucket(); require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual one.
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.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name. Example: examplebucket.
client.create_bucket('examplebucket')// Construct a request to create a bucket.
// Specify the bucket name.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("examplebucket");
// Specify the access control list (ACL) of the bucket.
// createBucketRequest.setBucketACL(CannedAccessControlList.Private);
// Specify the storage class of the bucket.
// createBucketRequest.setBucketStorageClass(StorageClass.Standard);
// Create the bucket asynchronously.
OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
@Override
public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
Log.d("asyncCreateBucket", "Success");
}
@Override
public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
// Request exception.
if (clientException != null) {
// Client-side exceptions, such as network errors.
clientException.printStackTrace();
}
if (serviceException != null) {
// Server-side exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the Endpoint of the region in which 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. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Specify the name, storage class, and ACL of the new bucket. */
CreateBucketRequest request(BucketName, StorageClass::IA, CannedAccessControlList::PublicReadWrite);
/* Set the data disaster recovery type to zone-redundant storage. */
//request.setDataRedundancyType(DataRedundancyType::ZRS);
/* Create the bucket. */
auto outcome = client.CreateBucket(request);
if (!outcome.isSuccess()) {
/* Handle the exception. */
std::cout << "CreateBucket fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}// Construct a request to create a bucket.
OSSCreateBucketRequest * create = [OSSCreateBucketRequest new];
// Set the bucket name to examplebucket.
create.bucketName = @"examplebucket";
// Set the access control list (ACL) of the bucket to private.
create.xOssACL = @"private";
// Set the storage class of the bucket to Infrequent Access (IA).
create.storageClass = OSSBucketStorageClassIA;
OSSTask * createTask = [client createBucket:create];
[createTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
NSLog(@"create bucket success!");
} else {
NSLog(@"create bucket failed, error: %@", task.error);
}
return nil;
}];
// Block the current thread to wait for the task to complete.
// [createTask waitUntilFinished]; #include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Set yourRegion to 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 char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize the aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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 set. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specifies whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* At the program entry point, call the aos_http_io_initialize method to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool for memory management is equivalent to apr_pool_t. The implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the new pool does not inherit from another memory pool. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as the endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
oss_acl_e oss_acl = OSS_ACL_PRIVATE;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
/* Assign the char* data to the aos_string_t bucket. */
aos_str_set(&bucket, bucket_name);
/* Create the bucket. */
resp_status = oss_create_bucket(oss_client_options, &bucket, oss_acl, &resp_headers);
/* Check whether the request was successful. */
if (aos_status_is_ok(resp_status)) {
printf("create bucket succeeded\n");
} else {
printf("create bucket failed\n");
}
/* Release the memory pool. This releases the memory allocated for various resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}API
Saat memanggil operasi PutBucket, Anda dapat menentukan nama dan region di header permintaan Host.
Kelas penyimpanan
OSS menyediakan lima kelas penyimpanan: Standard, Infrequent Access (IA), Archive, Cold Archive, dan Deep Cold Archive. Kelas penyimpanan default adalah Standard. Kelas-kelas ini memiliki biaya yang semakin rendah dan pembatasan akses yang semakin ketat sesuai dengan frekuensi akses data yang berbeda.
Objek secara default mewarisi kelas penyimpanan bucket. Meskipun Anda tidak dapat mengubah kelas penyimpanan bucket setelah dibuat, Anda dapat menggunakan aturan siklus hidup untuk secara otomatis mengubah kelas penyimpanan objek guna mengoptimalkan biaya.
Standard
Cocok untuk data aktif yang satu file-nya diakses lebih dari sekali per bulan. Mendukung akses waktu nyata. Ini adalah pilihan utama jika Anda tidak yakin tentang frekuensi akses data. Anda nanti dapat menggunakan aturan siklus hidup untuk secara otomatis mengubah objek ke kelas penyimpanan dengan biaya lebih rendah.
Infrequent Access (IA):
Cocok untuk data hangat yang satu file-nya diakses sekali per bulan atau kurang, seperti file backup dan log operasi. Mendukung akses waktu nyata tetapi memiliki durasi penyimpanan minimum 30 hari. Jika Anda menghapus objek sebelum 30 hari berlalu, Anda tetap dikenai biaya penyimpanan selama 30 hari. Kelas penyimpanan ini tidak cocok untuk data sementara atau uji coba.
Archive:
Cocok untuk data dingin yang satu file-nya diakses kurang dari sekali setiap 90 hari. Mendukung akses waktu nyata untuk objek Arsip. Anda juga dapat memilih untuk memulihkan objek terlebih dahulu lalu membacanya. Pemulihan membutuhkan waktu sekitar 1 menit. Kelas ini memiliki durasi penyimpanan minimum 60 hari.
Restore: Mengubah kembali status data menjadi dapat diakses. Proses ini memerlukan waktu tunggu.
Cold Archive
Cocok untuk data yang satu file-nya diakses kurang dari sekali per tahun. Anda harus memulihkan data terlebih dahulu sebelum dapat membacanya. Pemulihan membutuhkan waktu 1 hingga 12 jam. Kelas ini memiliki biaya lebih rendah dan durasi penyimpanan minimum 180 hari.
Deep Cold Archive
Ini adalah opsi dengan biaya terendah dan cocok untuk data yang satu file-nya diakses kurang dari sekali per tahun. Pemulihan membutuhkan waktu 12 atau 48 jam. Kelas ini memiliki durasi penyimpanan minimum 180 hari. Membuat bucket dengan kelas penyimpanan ini tidak disarankan. Kami menyarankan agar Anda menggunakan aturan siklus hidup untuk secara otomatis mengubah data ke kelas ini.
Konsol
Saat membuat bucket, Anda dapat mengonfigurasi kelas penyimpanan bucket sesuai kebutuhan Anda.
ossutil
Perintah berikut membuat bucket bernama examplebucket dengan kelas penyimpanan Infrequent Access (IA).
ossutil mb oss://examplebucket --storage-class IAUntuk informasi selengkapnya tentang perintah ini, lihat mb (buat bucket).
SDK OSS
Contoh kode berikut menunjukkan cara membuat bucket menggunakan SDK umum. Untuk contoh kode SDK lainnya, lihat Pengenalan SDK.
Java
Untuk mengatur kelas penyimpanan, Anda dapat mengonfigurasi objek CreateBucketRequest sebagai berikut.
// Prepare a request object that contains the storage class.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setStorageClass(StorageClass.IA); // Specify the storage class here.
// Options: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.Untuk contoh lengkap, lihat Buat bucket (Java SDK V1).
Python
Saat memanggil metode client.put_bucket, Anda dapat menentukan kelas penyimpanan menggunakan parameter create_bucket_configuration.
# Prepare a request object that contains the storage class.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
storage_class='IA' # Specify the storage class here.
)
)
# Options: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'Untuk contoh lengkap, lihat Buat bucket (Python SDK V2).
Go
Untuk mengatur kelas penyimpanan, Anda dapat mengonfigurasi field CreateBucketConfiguration saat membuat PutBucketRequest.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
StorageClass: oss.StorageClassIA, // Specify the storage class here.
},
}
// Options: oss.StorageClassStandard, oss.StorageClassIA, oss.StorageClassArchive, etc.Untuk contoh lengkap, lihat Buat bucket (Go SDK V2).
PHP
Untuk mengatur kelas penyimpanan, Anda dapat meneruskan objek CreateBucketConfiguration ke konstruktor saat membuat objek PutBucketRequest.
// Prepare a request object that contains configurations such as the storage class.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
null, // acl
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
'IA', // Specify the storage class here.
)
);
/*
* Optional storage classes: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'
*/Untuk contoh lengkap, lihat Buat bucket (PHP SDK V2).
C#
Untuk mengatur kelas penyimpanan, Anda dapat membuat objek CreateBucketRequest dan mengonfigurasi propertinya sebagai berikut.
// Prepare a request object that contains the storage class configuration.
var request = new CreateBucketRequest("your-bucket-name");
request.StorageClass = StorageClass.IA; // Specify the storage class here.
// Optional storage classes: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.Untuk contoh lengkap, lihat Buat bucket (C# SDK V1).
Node.js
Untuk mengatur kelas penyimpanan, Anda dapat membuat objek options dan meneruskannya ke metode putBucket.
// Prepare an options object that contains the storage class configuration.
const options = {
storageClass: 'IA', // Specify the storage class here.
};
// Optional storage classes: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'Untuk contoh lengkap, lihat Buat bucket (Node.js SDK).
Android
Untuk mengatur kelas penyimpanan atau izin akses, Anda dapat membuat dan mengonfigurasi objek CreateBucketRequest sebagai berikut.
// Prepare a request object that contains configurations such as the storage class.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setBucketStorageClass(StorageClass.IA); // Specify the storage class here.
// Optional storage classes: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.Untuk contoh lengkap, lihat Buat bucket (Android SDK).
iOS
Untuk mengatur kelas penyimpanan, buat objek OSSCreateBucketRequest dan konfigurasi properti berikut.
// Prepare a request object that contains configurations such as the storage class.
OSSCreateBucketRequest *create = [OSSCreateBucketRequest new];
create.bucketName = @"your-bucket-name";
create.storageClass = OSSBucketStorageClassIA; // Specify the storage class here.
// Optional storage classes: OSSBucketStorageClassStandard, OSSBucketStorageClassIA, etc.Untuk contoh lengkap, lihat Buat bucket (iOS SDK).
API
Saat memanggil PutBucket, Anda dapat menentukan kelas penyimpanan bucket di elemen permintaan StorageClass.
Jenis redundansi penyimpanan
Jenis redundansi data menentukan tingkat pemulihan bencana, daya tahan, dan ketersediaan data Anda. Jenis default adalah penyimpanan redundan zona. Anda dapat upgrade dari penyimpanan redundan lokal ke penyimpanan redundan zona, tetapi tidak dapat menurunkan spesifikasi.
Penyimpanan Redundan Zona (ZRS) – Direkomendasikan untuk lingkungan produksi
Data Anda disimpan di beberapa zona (AZ) dalam region yang sama. Ini menjamin kelangsungan bisnis jika seluruh zona mengalami kegagalan dan memberikan daya tahan serta ketersediaan layanan yang lebih tinggi.
Penyimpanan redundan lokal (LRS) - Untuk data non-kritis atau uji coba
Data Anda disimpan secara redundan dalam satu zona dengan biaya lebih rendah. Dapat menahan kegagalan perangkat keras tetapi tidak dapat menjamin akses data jika zona mengalami kegagalan.
Konsol
Saat membuat bucket, Anda dapat memilih jenis redundansi data untuk bucket di bawah Jenis Redundansi Penyimpanan.
Gunakan ossutil
Perintah berikut membuat bucket bernama examplebucket dengan jenis redundansi penyimpanan redundan lokal (LRS).
ossutil mb oss://examplebucket --redundancy-type LRSUntuk informasi selengkapnya tentang perintah ini, lihat mb (buat bucket).
Gunakan SDK OSS
Java
Untuk mengatur jenis redundansi penyimpanan, Anda dapat mengonfigurasi objek CreateBucketRequest sebagai berikut.
// Prepare a request object that contains the storage redundancy type.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS); // Specify the storage redundancy type here.
// Options: DataRedundancyType.ZRS, DataRedundancyType.LRSUntuk contoh lengkap, lihat Buat bucket (Java SDK V1).
Python
Saat memanggil metode client.put_bucket, Anda dapat menentukan jenis redundansi penyimpanan menggunakan parameter create_bucket_configuration.
# Prepare a request object that contains the storage redundancy type.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
data_redundancy_type='ZRS' # Specify the storage redundancy type here.
)
)
# Options: 'ZRS', 'LRS'Untuk contoh lengkap, lihat Buat bucket (Python SDK V2).
Go
Untuk mengatur jenis redundansi penyimpanan, Anda dapat mengonfigurasi field CreateBucketConfiguration saat membuat PutBucketRequest.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
DataRedundancyType: oss.DataRedundancyZRS, // Specify the storage redundancy type here.
},
}
// Options: oss.DataRedundancyZRS, oss.DataRedundancyLRSUntuk contoh lengkap, lihat Buat bucket (Go SDK V2).
PHP
Untuk mengatur jenis redundansi penyimpanan, Anda dapat meneruskan objek CreateBucketConfiguration ke konstruktor saat membuat objek PutBucketRequest.
// Prepare a request object that contains configurations such as the storage redundancy type.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
null, // acl
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
null, // Specify the storage redundancy type here.
'ZRS'
)
);
/*
* Optional storage redundancy types: 'ZRS', 'LRS'
*/Untuk contoh lengkap, lihat Buat bucket (PHP SDK V2).
C#
Untuk mengatur jenis redundansi penyimpanan, Anda dapat membuat objek CreateBucketRequest dan mengonfigurasi propertinya sebagai berikut.
// Prepare a request object that contains the storage redundancy type configuration.
var request = new CreateBucketRequest("your-bucket-name");
request.DataRedundancyType = DataRedundancyType.ZRS; // Specify the storage redundancy type here.
// Optional storage redundancy types: DataRedundancyType.ZRS, DataRedundancyType.LRSUntuk contoh lengkap, lihat Buat bucket (C# SDK V1).
Node.js
Untuk mengatur jenis redundansi penyimpanan, Anda dapat membuat objek options dan meneruskannya ke metode putBucket.
// Prepare an options object that contains the storage redundancy type configuration.
const options = {
dataRedundancyType: 'LRS', // Specify the storage redundancy type here.
};
// Optional storage redundancy types: 'ZRS', 'LRS'Untuk contoh lengkap, lihat Buat bucket (Node.js SDK).
API
Saat memanggil PutBucket, Anda dapat menentukan jenis redundansi penyimpanan bucket di elemen permintaan DataRedundancyType.
Daftar kontrol akses (ACL)
Daftar kontrol akses (ACL) mengontrol kebijakan akses anonim untuk bucket. Izin default adalah privat, yang dapat Anda ubah kapan saja setelah bucket dibuat. Objek secara default mewarisi izin akses bucket. Anda juga dapat mengatur izin untuk objek individual.
Privat - Sangat direkomendasikan
Ini adalah pengaturan default dan paling aman. Hanya pemilik bucket dan pengguna yang secara eksplisit diberikan izin melalui kebijakan RAM atau kebijakan bucket yang dapat mengakses bucket. Disarankan selalu menggunakan pengaturan ini. Untuk memberikan akses kepada pengguna lain, lihat Ikhtisar pengelolaan izin dan kontrol akses.
Baca-publik – Gunakan dengan hati-hati
Tidak memerlukan autentikasi. Siapa pun, termasuk pengunjung anonim, dapat membaca objek tetapi tidak dapat menulisnya.
Data Anda akan sepenuhnya publik. Hal ini dapat mengakibatkan biaya tak terduga untuk lalu lintas keluar melalui Internet. Pengaturan ini cocok untuk skenario yang memerlukan berbagi publik, seperti hosting sumber daya website statis.
Jika Anda harus mengaktifkan baca-publik, disarankan mengonfigurasi Perlindungan hotlink untuk memungkinkan akses hanya dari sumber tertentu, seperti domain website Anda, guna mencegah konsumsi traffic jahat.
Baca-tulis publik - Sangat tidak disarankan
Siapa pun dapat membaca, menulis, bahkan menghapus objek dalam bucket. Ini menimbulkan risiko sangat tinggi dan dapat mengakibatkan biaya besar. Gunakan pengaturan ini hanya untuk skenario khusus, seperti repositori sumber daya publik. Pengaturan ini dilarang keras untuk penggunaan umum.
Gunakan Konsol OSS
Karena alasan keamanan, Konsol OSS secara default mengaktifkan Blokir Akses Publik dan hanya mendukung pembuatan bucket privat.
Untuk mengubah ACL menjadi baca-publik atau baca-tulis publik, Anda dapat melakukan langkah-langkah berikut:
Klik nama bucket target.
Pada panel navigasi di sebelah kiri, pilih Access Control > Block Public Access dan nonaktifkan kebijakan tersebut.
Buka tab Access Control List dan klik Settings.
Ikuti petunjuk di layar untuk mengubah ACL bucket menjadi Public Read atau Public Read/Write.
Gunakan ossutil
Perintah berikut membuat bucket bernama examplebucket dan mengatur daftar kontrol aksesnya (ACL) menjadi privat.
ossutil mb oss://examplebucket --acl=privateUntuk informasi selengkapnya tentang perintah ini, lihat mb (buat bucket).
Gunakan SDK OSS
Java
Untuk mengatur izin akses, Anda dapat mengonfigurasi objek CreateBucketRequest sebagai berikut.
// Prepare a request object that contains the access permissions.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setCannedACL(CannedAccessControlList.private); // Specify the bucket ACL here.
// Options: CannedAccessControlList.private, CannedAccessControlList.PublicRead,CannedAccessControlList.PublicReadWriteUntuk contoh lengkap, lihat Buat bucket (Java SDK V1).
Python
Saat memanggil metode client.put_bucket, Anda dapat menentukan izin akses menggunakan parameter create_bucket_configuration.
# Prepare a request object that contains the access permissions.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
access_control_policy='pricate' # Specify the access permissions here.
)
)
# Options: 'pricate', 'public-read','public-read-write'Untuk contoh lengkap, lihat Buat bucket (Python SDK V2).
Go
Untuk mengatur izin akses, Anda dapat mengonfigurasi field Acl saat membuat PutBucketRequest.
// Prepare a request object that contains configurations such as access permissions.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
Acl: oss.BucketACLPrivate, // Specify the access permissions here.
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
},
}
// Optional access permissions: oss.BucketACLPrivate, oss.BucketACLPublicRead, oss.BucketACLPublicReadWriteUntuk contoh lengkap, lihat Buat bucket (Go SDK V2).
PHP
Untuk mengatur izin akses, Anda dapat mengonfigurasi field Acl saat membuat PutBucketRequest.
// Prepare a request object that contains configurations such as access permissions.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
'private', // Specify the access permissions here (second parameter).
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
'IA', // Specify the storage class here.
'ZRS' // Specify the redundancy type here.
)
);
/*
* Optional access permissions: 'private', 'public-read', 'public-read-write'
*/Untuk contoh lengkap, lihat Buat bucket (PHP SDK V2).
C#
Untuk mengatur izin akses, Anda dapat membuat objek CreateBucketRequest dan mengonfigurasi propertinya sebagai berikut.
// Prepare a request object that contains the access permission configuration.
var request = new CreateBucketRequest("your-bucket-name");
request.ACL = CannedAccessControlList.private; // Specify the access permissions here.
// Optional access permissions: CannedAccessControlList.private, CannedAccessControlList.PublicRead,CannedAccessControlList.PublicReadWriteUntuk contoh lengkap, lihat Buat bucket (C# SDK V1).
Node.js
Untuk mengatur izin akses, Anda dapat membuat objek options dan meneruskannya ke metode putBucket.
// Prepare an options object that contains the access permissions.
const options = {
acl: 'private', // Specify the access permissions here.
};
// Optional access permissions: 'private', 'public-read','public-read-write'Untuk contoh lengkap, lihat Buat bucket (Node.js SDK).
Android
Untuk mengatur izin akses, Anda dapat membuat dan mengonfigurasi objek CreateBucketRequest sebagai berikut.
// Prepare a request object that contains configurations such as access permissions.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setBucketACL(CannedAccessControlList.Private); // Specify the access permissions here.
// Optional access permissions: CannedAccessControlList.Private, CannedAccessControlList.PublicRead,CannedAccessControlList.PublicReadWriteUntuk contoh lengkap, lihat Buat bucket (Android SDK).
iOS
Untuk mengatur izin akses, Anda dapat membuat objek OSSCreateBucketRequest dan mengonfigurasi propertinya sebagai berikut.
// Prepare a request object that contains configurations such as access permissions.
OSSCreateBucketRequest *create = [OSSCreateBucketRequest new];
create.bucketName = @"your-bucket-name";
create.xOssACL = @"private"; // Specify the access permissions here.
// Optional access permissions: private,public-read, public-read-write, etc.Untuk contoh lengkap, lihat Buat bucket (iOS SDK).
API
Saat memanggil operasi PutBucket, Anda dapat menentukan ACL bucket di header permintaan x-oss-acl.
Blokir Akses Publik
Ini adalah sakelar keamanan global yang mencegah paparan publik data secara tidak sengaja akibat konfigurasi ACL atau kebijakan bucket yang salah.
Saat diaktifkan, Anda hanya dapat membuat bucket privat. Anda tidak dapat mengatur ACL baca-publik atau baca-tulis publik, atau membuat kebijakan bucket dengan semantik akses publik. Secara default, Blokir Akses Publik diaktifkan saat Anda membuat bucket di OSS. Jika bisnis Anda memerlukan akses publik, Anda dapat menonaktifkan fitur ini secara manual setelah bucket dibuat. Namun, demi alasan keamanan, kami tidak menyarankan Anda menonaktifkannya.
Konfigurasi fitur opsional
Anda dapat mengonfigurasi fitur-fitur ini selama atau setelah pembuatan bucket sesuai kebutuhan bisnis Anda.
Versioning
Fitur ini mencegah penghapusan atau penimpaan data secara tidak sengaja. Saat Anda mengunggah objek dengan nama yang sama, versi baru dibuat alih-alih menimpa yang sudah ada. Anda dapat memulihkan versi sebelumnya dengan satu klik setelah operasi tidak sengaja. Untuk informasi selengkapnya, lihat Versioning.
Enkripsi sisi server
Fitur ini secara otomatis mengenkripsi data statis. OSS mengenkripsi data saat ditulis dan mendekripsinya saat dibaca. Disarankan mengaktifkan setidaknya opsi 'Fully managed by OSS'. Untuk informasi selengkapnya, lihat Enkripsi sisi server.
Kelompok sumber daya
Fitur ini cocok untuk kolaborasi multi-tim. Anda dapat mengelompokkan bucket berdasarkan departemen atau proyek untuk pengelolaan izin dan akuntansi biaya yang independen. Untuk informasi selengkapnya, lihat Gunakan kelompok sumber daya.
Kueri log waktu nyata
Saat fitur ini diaktifkan, Anda dapat dengan cepat mengkueri dan menganalisis log akses di konsol untuk melihat siapa yang mengakses file mana dan kapan. Hal ini membantu Anda menyelidiki akses tidak biasa atau melakukan analisis perilaku pengguna. Untuk informasi selengkapnya, lihat Kueri log waktu nyata.
Backup terjadwal
Fitur ini mendukung pencadangan data otomatis. Untuk informasi selengkapnya, lihat Konfigurasi backup terjadwal untuk bucket.
Layanan HDFS
Fitur ini cocok untuk skenario data lake. Memungkinkan framework data besar seperti Spark untuk langsung menganalisis data OSS tanpa migrasi data. Untuk informasi selengkapnya, lihat Apa itu layanan OSS-HDFS?.
Bucket Tagging
Fitur ini memfasilitasi manajemen batch dan analisis biaya. Anda dapat mengklasifikasikan bucket menggunakan tag pasangan kunci-nilai, seperti
department:research. Untuk informasi selengkapnya, lihat Kelola tag bucket.
Deskripsi penagihan
Membuat bucket gratis. Anda dikenai biaya berdasarkan penggunaan aktual setelah menyimpan data di bucket. Untuk menghindari biaya yang tidak perlu, perhatikan poin-poin berikut saat mengonfigurasi bucket Anda:
Sesuaikan redundansi penyimpanan dengan paket sumber daya
Jenis paket sumber daya harus persis sesuai dengan jenis redundansi penyimpanan bucket. Misalnya, paket sumber daya LRS (penyimpanan redundan lokal) tidak dapat digunakan untuk mengimbangi biaya bucket ZRS (penyimpanan redundan zona), dan sebaliknya. Pastikan pilihan Anda saat pembuatan.Penagihan khusus untuk kelas penyimpanan non-Standard
Meskipun kelas penyimpanan Infrequent Access, Archive, Cold Archive, dan Deep Cold Archive memiliki harga satuan lebih rendah, kelas-kelas ini memiliki durasi penyimpanan minimum dan dikenai biaya pengambilan data.Penghapusan atau modifikasi dini: Jika file dihapus atau dimodifikasi sebelum durasi penyimpanan minimum terpenuhi, OSS tetap mengenakan biaya penyimpanan untuk durasi yang tersisa.
Pembacaan data: Kecuali kelas penyimpanan Standard, mengakses data di kelas penyimpanan lainnya dikenai biaya pengambilan data tambahan.
Risiko akses publik
Jika Anda mengatur daftar kontrol akses (ACL) menjadi baca-publik atau baca-tulis publik, data Anda terpapar ke Internet. Hal ini dapat menyebabkan konsumsi traffic jahat dan mengakibatkan biaya traffic yang tidak terduga tinggi.