创建双区域存储桶

创建双区域存储桶

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档


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 region1 = "your-region1-name",
        string region2 = "your-region2-name")
    {
        var client = StorageClient.Create();

        // Two regions will be concatenated with a '+' to form dual region string, e.g. "US-EAST1+US-WEST1".
        string dualRegion = $"{region1}+{region2}";

        var bucket = new Bucket
        {
            Name = bucketName,
            Location = dualRegion
        };
        var storageBucket = client.CreateBucket(projectId, bucket);

        Console.WriteLine($"Created storage bucket {storageBucket.Name} in {storageBucket.Location} with location-type {storageBucket.LocationType}.");
        return storageBucket;
    }

}

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

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_location(region_a + '+' + region_b));
  if (!metadata) throw std::runtime_error(metadata.status().message());

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

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

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

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

// createBucketDualRegion creates a new dual-region bucket in the project in the
// provided locations.
func createBucketDualRegion(w io.Writer, projectID, bucketName, region1, region2 string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	// region1 := "US-EAST1"
	// region2 := "US-WEST1"

	ctx := context.Background()

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

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

	storageLocation := &storage.BucketAttrs{
		Location: fmt.Sprintf("%s+%s", region1, region2),
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, storageLocation); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v in %v\n", bucketName, storageLocation.Location)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class CreateBucketDualRegion {

  public static void createBucketDualRegion(
      String projectId, String bucketName, 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";

    // 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";

    // Construct the dual region ie. "US-EAST1+US-WEST1"
    String dualRegion = firstRegion + "+" + secondRegion;

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

    Bucket bucket =
        storage.create(BucketInfo.newBuilder(bucketName).setLocation(dualRegion).build());

    System.out.println(
        "Created bucket " + bucket.getName() + " in location " + bucket.getLocation());
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * 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 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: `${region1}+${region2}`, // e.g. `US-EAST1+US-WEST1`
  });

  console.log(`${bucket.name} created in '${region1}+${region2}'`);
}

createDualRegionBucket().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

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.
 * @param string $location1 First location for the bucket's regions. Case-insensitive.
 * @param string $location2 Second location for the bucket's regions. Case-insensitive.
 */
function create_bucket_dual_region($bucketName, $location1, $location2)
{
    // $bucketName = 'my-bucket';
    // $location1 = 'US-EAST1';
    // $location2 = 'US-WEST1';

    $storage = new StorageClient();
    $bucket = $storage->createBucket($bucketName, [
        'location' => "${location1}+${location2}",
    ]);

    printf("Created dual-region bucket '%s' in '%s+%s'", $bucket->name(), $location1, $location2);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def create_bucket_dual_region(bucket_name, region_1, region_2):
    """Creates a Dual-Region Bucket with provided locations."""
    # 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"

    storage_client = storage.Client()
    storage_client.create_bucket(bucket_name, location=f"{region_1}+{region_2}")

    print(f"Bucket {bucket_name} created in {region_1}+{region_2}.")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# 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,
                                location: "#{region_1}+#{region_2}"

puts "Bucket #{bucket.name} created in #{bucket.location}."

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器