Menggunakan penyimpanan dual-region

Ringkasan

Halaman ini menjelaskan cara menggunakan penyimpanan dual-region.

Peran yang diperlukan

Guna mendapatkan izin yang diperlukan untuk membuat bucket dengan region ganda, minta administrator Anda untuk memberi Anda peran IAM Storage Admin (roles/storage.admin) untuk project tersebut.

Peran standar ini berisi izin yang diperlukan untuk membuat bucket dengan region ganda. Untuk melihat izin persis yang diperlukan, luaskan bagian Izin yang diperlukan:

Izin yang diperlukan

  • storage.buckets.create
  • storage.buckets.enableObjectRetention (hanya diperlukan jika mengaktifkan konfigurasi retensi objek untuk bucket)
  • storage.buckets.list (hanya diperlukan jika membuat bucket menggunakan Konsol Google Cloud)
  • resourcemanager.projects.get (hanya diperlukan jika membuat bucket menggunakan Konsol Google Cloud)

Anda mungkin juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaan lainnya. Untuk melihat peran yang terkait dengan izin tertentu, lihat Peran IAM untuk Cloud Storage.

Untuk mengetahui petunjuk tentang cara memberikan peran untuk project, baca bagian Mengelola akses ke project.

Membuat bucket region ganda

Selesaikan langkah-langkah berikut untuk membuat bucket dual-region:

Konsol

  1. Di Konsol Google Cloud, buka halaman Bucket Cloud Storage.

    Buka Bucket

  2. Klik Create.

  3. Di halaman Buat bucket, masukkan informasi bucket Anda. Untuk melanjutkan ke langkah berikutnya, klik Lanjutkan.

    1. Untuk Beri nama bucket Anda, masukkan nama yang memenuhi persyaratan penamaan bucket.

    2. Untuk Pilih tempat untuk menyimpan data, di samping Jenis lokasi, pilih Dual-region. Opsional: Anda dapat menggabungkan fitur ini dengan replikasi turbo, dengan mencentang kotak Tambahkan replikasi turbo.

    3. Untuk Lokasi, pilih Benua dan Region terkait yang ingin Anda gunakan.

    4. Untuk Pilih kelas penyimpanan default untuk data Anda, pilih kelas penyimpanan untuk bucket. Kelas penyimpanan default ditetapkan secara default pada semua objek yang diupload ke bucket.

    5. Untuk Pilih cara mengontrol akses ke objek, pilih opsi pencegahan akses publik dan kontrol akses yang ingin Anda gunakan.

    6. Untuk Memilih cara melindungi data objek, pilih alat perlindungan yang ingin Anda gunakan sepertipembuatan versi objek, kebijakan retensi , danmetode enkripsi.

  4. Klik Create.

    Untuk mempelajari cara mendapatkan informasi error mendetail tentang operasi Cloud Storage yang gagal di Konsol Google Cloud, lihat Pemecahan masalah.

Command line

Gunakan perintah buckets create dengan flag --location dan --placement:

gcloud storage buckets create gs://BUCKET_NAME --location=MULTI-REGION --placement=REGION_1,REGION_2

Dengan keterangan:

  • BUCKET_NAME adalah nama bucket yang Anda buat. Misalnya, my-bucket

  • MULTI-REGION menentukan kode multi-region yang terkait dengan region yang mendasarinya. Misalnya, saat memilih region ASIA-SOUTH1 (Mumbai) dan ASIA-SOUTH2 (Delhi), gunakan IN.

  • REGION_1 menentukan lokasi geografis region untuk bucket Anda. Contoh, ASIA-EAST1.

  • REGION_2 menentukan lokasi geografis region kedua untuk bucket Anda. Contoh, ASIA-SOUTHEAST1.

Jika permintaan berhasil, perintah akan menampilkan pesan berikut:

Creating gs://BUCKET_NAME/...

Untuk daftar lengkap opsi yang tersedia saat membuat bucket dengan gcloud storage, lihat opsi buckets create.

Library klien

C++

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& region_a, std::string const& region_b) {
  auto metadata = client.CreateBucket(
      bucket_name,
      gcs::BucketMetadata().set_custom_placement_config(
          gcs::BucketCustomPlacementConfig{{region_a, region_b}}));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Bucket " << metadata->name() << " created."
            << "\nFull Metadata: " << *metadata << "\n";
}

C#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class CreateDualRegionBucketSample
{
    public Bucket CreateDualRegionBucket(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string location = "your-location",
        string region1 = "your-region1-name",
        string region2 = "your-region2-name")
    {
        var client = StorageClient.Create();

        var bucket = new Bucket
        {
            Name = bucketName,
            Location = location,
            CustomPlacementConfig = new Bucket.CustomPlacementConfigData
            {
                DataLocations = new[] { region1, region2 }
            }
        };

        var storageBucket = client.CreateBucket(projectId, bucket);

        Console.WriteLine($"Created storage bucket {storageBucket.Name}" +
            $" in {storageBucket.Location}" +
            $" with location-type {storageBucket.LocationType} and" +
            $" dataLocations {string.Join(",", storageBucket.CustomPlacementConfig.DataLocations)}.");

        return storageBucket;
    }

}

Go

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// createBucketDualRegion creates a new dual-region bucket in the project in the
// provided location and regions.
// See https://cloud.google.com/storage/docs/locations#location-dr for more information.
func createBucketDualRegion(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	location := "US"
	region1 := "US-EAST1"
	region2 := "US-WEST1"

	ctx := context.Background()

	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	storageDualRegion := &storage.BucketAttrs{
		Location: location,
		CustomPlacementConfig: &storage.CustomPlacementConfig{
			DataLocations: []string{region1, region2},
		},
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, storageDualRegion); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
	}

	attrs, err := bucket.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v", bucketName)
	fmt.Fprintf(w, " - location: %v", attrs.Location)
	fmt.Fprintf(w, " - locationType: %v", attrs.LocationType)
	fmt.Fprintf(w, " - customPlacementConfig.dataLocations: %v", attrs.CustomPlacementConfig.DataLocations)
	return nil
}

Java

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.BucketInfo.CustomPlacementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Arrays;

public class CreateBucketDualRegion {

  public static void createBucketDualRegion(
      String projectId,
      String bucketName,
      String location,
      String firstRegion,
      String secondRegion) {
    // The ID of your GCP project.
    // String projectId = "your-project-id";

    // The ID to give your GCS bucket.
    // String bucketName = "your-unique-bucket-name";

    // The location your dual regions will be located in.
    // String location = "US";

    // One of the regions the dual region bucket is to be created in.
    // String firstRegion = "US-EAST1";

    // The second region the dual region bucket is to be created in.
    // String secondRegion = "US-WEST1";

    // See this documentation for other valid locations and regions:
    // https://cloud.google.com/storage/docs/locations

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    CustomPlacementConfig config =
        CustomPlacementConfig.newBuilder()
            .setDataLocations(Arrays.asList(firstRegion, secondRegion))
            .build();

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setLocation(location)
            .setCustomPlacementConfig(config)
            .build();

    Bucket bucket = storage.create(bucketInfo);

    System.out.println(
        "Created bucket "
            + bucket.getName()
            + " in location "
            + bucket.getLocation()
            + " with location type "
            + bucket.getLocationType()
            + " with Custom Placement Config "
            + bucket.getCustomPlacementConfig().toString());
  }
}

Node.js

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The bucket's pair of regions. Case-insensitive.
// See this documentation for other valid locations:
// https://cloud.google.com/storage/docs/locations
// const location = 'US';
// const region1 = 'US-EAST1';
// const region2 = 'US-WEST1';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
// The bucket in the sample below will be created in the project associated with this client.
// For more information, please see https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.html
const storage = new Storage();

async function createDualRegionBucket() {
  // For regions supporting dual-regions see: https://cloud.google.com/storage/docs/locations
  const [bucket] = await storage.createBucket(bucketName, {
    location,
    customPlacementConfig: {
      dataLocations: [region1, region2],
    },
  });

  console.log(`Created '${bucket.name}'`);
  console.log(`- location: '${bucket.metadata.location}'`);
  console.log(`- locationType: '${bucket.metadata.locationType}'`);
  console.log(
    `- customPlacementConfig: '${JSON.stringify(
      bucket.metadata.customPlacementConfig
    )}'`
  );
}

createDualRegionBucket().catch(console.error);

PHP

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

use Google\Cloud\Storage\StorageClient;

/**
 * Create a new bucket with a custom default storage class and location.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $location Location for the bucket's regions. Case-insensitive.
 *        (e.g. 'US')
 * @param string $region1 First region for the bucket's regions. Case-insensitive.
 *        (e.g. 'US-EAST1')
 * @param string $region2 Second region for the bucket's regions. Case-insensitive.
 *        (e.g. 'US-WEST1')
 */
function create_bucket_dual_region(string $bucketName, string $location, string $region1, string $region2): void
{
    $storage = new StorageClient();
    $bucket = $storage->createBucket($bucketName, [
        'location' => $location,
        'customPlacementConfig' => [
            'dataLocations' => [$region1, $region2],
        ],
    ]);

    $info = $bucket->info();

    printf("Created '%s':", $bucket->name());
    printf("- location: '%s'", $info['location']);
    printf("- locationType: '%s'", $info['locationType']);
    printf("- customPlacementConfig: '%s'" . PHP_EOL, print_r($info['customPlacementConfig'], true));
}

Python

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import storage

def create_bucket_dual_region(bucket_name, location, region_1, region_2):
    """Creates a Dual-Region Bucket with provided location and regions.."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The bucket's pair of regions. Case-insensitive.
    # See this documentation for other valid locations:
    # https://cloud.google.com/storage/docs/locations
    # region_1 = "US-EAST1"
    # region_2 = "US-WEST1"
    # location = "US"

    storage_client = storage.Client()
    bucket = storage_client.create_bucket(bucket_name, location=location, data_locations=[region_1, region_2])

    print(f"Created bucket {bucket_name}")
    print(f" - location: {bucket.location}")
    print(f" - location_type: {bucket.location_type}")
    print(f" - customPlacementConfig data_locations: {bucket.data_locations}")

Ruby

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

# The ID of your GCS bucket
# bucket_name = "your-bucket-name"

# The bucket's pair of regions. Case-insensitive.
# See this documentation for other valid locations:
# https://cloud.google.com/storage/docs/locations
# region_1 = "US-EAST1"
# region_2 = "US-WEST1"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.create_bucket bucket_name,
                                custom_placement_config: { data_locations: [region_1, region_2] }

puts "Bucket #{bucket.name} created:"
puts "- location: #{bucket.location}"
puts "- location_type: #{bucket.location_type}"
puts "- custom_placement_config:"
puts "  - data_locations: #{bucket.data_locations}"

REST API

JSON API

  1. Telah menginstal dan melakukan inisialisasigcloud CLI, agar dapat membuat token akses untuk header Authorization.

    Atau, Anda dapat membuat token akses menggunakan OAuth 2.0 Playground dan menyertakannya di header Authorization.

  2. Buat file JSON yang berisi setelan untuk bucket, yang harus menyertakan name dan location. Lihat dokumentasi Buckets:Insert untuk daftar lengkap setelan. Berikut adalah setelan umum yang harus disertakan:

    {
      "name": "BUCKET_NAME",
      "location": "MULTI-REGION",
      "customPlacementConfig": {
        "dataLocations": ["REGION_1", "REGION_2"]
        },
      "storageClass": "STORAGE_CLASS"
    }

    Dengan keterangan:

    • BUCKET_NAME adalah nama yang ingin Anda berikan untuk bucket, tunduk pada persyaratan penamaan. Contohnya, my-bucket.
    • MULTI-REGION menentukan kode multi-region yang terkait dengan region yang mendasarinya. Misalnya, saat memilih region ASIA-SOUTH1 (Mumbai) dan ASIA-SOUTH2 (Delhi), gunakan IN.
    • REGION_1 dan REGION_2 adalah region tempat Anda ingin menyimpan data objek bucket. Misalnya, ASIA-EAST1 dan ASIA-SOUTHEAST1.
    • STORAGE_CLASS adalah kelas penyimpanan dari bucket Anda. Misalnya, STANDARD
  3. Gunakan cURL untuk memanggil JSON API:

    curl -X POST --data-binary @JSON_FILE_NAME \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json" \
     "https://storage.googleapis.com/storage/v1/b?project=PROJECT_ID"

    Dengan keterangan:

    • JSON_FILE_NAME adalah nama file JSON yang Anda buat di Langkah 2.
    • PROJECT_ID adalah ID project yang akan dikaitkan dengan bucket Anda. Misalnya, my-project

XML API

  1. Telah menginstal dan melakukan inisialisasigcloud CLI, agar dapat membuat token akses untuk header Authorization.

    Atau, Anda dapat membuat token akses menggunakan OAuth 2.0 Playground dan menyertakannya di header Authorization.

  2. Buat file XML yang berisi informasi berikut:

      <CreateBucketConfiguration>
         <LocationConstraint>MULTI-REGION</LocationConstraint>
            <CustomPlacementConfig>
               <DataLocations>
                  <DataLocation>REGION_1</DataLocation>
                  <DataLocation>REGION_2</DataLocation>
               </DataLocations>
            </CustomPlacementConfig>
         <StorageClass>STORAGE_CLASS</StorageClass>
      </CreateBucketConfiguration>
     

    Dengan keterangan:

    • MULTI-REGION menentukan kode multi-region yang terkait dengan region yang mendasarinya. Misalnya, saat memilih region ASIA-SOUTH1 (Mumbai) dan ASIA-SOUTH2 (Delhi), gunakan IN.
    • REGION_1 dan REGION_2 adalah region tempat Anda ingin menyimpan data objek bucket. Misalnya, ASIA-EAST1 dan ASIA-SOUTHEAST1.
    • STORAGE_CLASS adalah kelas penyimpanan default untuk bucket Anda. Misalnya, STANDARD

  3. Gunakan cURL untuk memanggil XML API:

      curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-project-id: PROJECT_ID" \
      "https://storage.googleapis.com/BUCKET_NAME"
    

    Dengan keterangan:

    • XML_FILE_NAME adalah nama file XML yang Anda buat di Langkah 2.
    • PROJECT_ID adalah ID project yang akan dikaitkan dengan bucket Anda. Contoh, my-project.
    • BUCKET_NAME adalah nama yang ingin Anda berikan untuk bucket, tunduk pada persyaratan penamaan. Contohnya, my-bucket.

    Jika permintaan menyertakan region yang tidak didukung, pesan error akan ditampilkan. Jika permintaan berhasil, respons tidak akan ditampilkan.

Langkah selanjutnya