创建存储分区

本页面介绍如何创建 Cloud Storage 存储分区。如需查看存储分区的概览,请参阅关键术语。如果您的请求中没有指定,则系统会在 US 多区域创建存储分区,并且其默认存储类别为 Standard 存储空间

创建新存储桶

如需创建新的存储桶,请完成以下步骤:

控制台

  1. 在 Google Cloud Console 中,转到 Cloud Storage 浏览器页面。

    转到浏览器

  2. 点击创建存储分区
  3. 创建存储分区页面上,输入您的存储分区信息。如需转到下一步,请点击继续
    • 指定存储分区的名称中,输入符合存储分区名称要求的名称。
    • 选择存储数据的位置部分,选择 位置类型位置,将永久存储存储分区数据。
    • 为您的数据选择默认存储类别中,为存储分区选择存储类别。默认情况下,系统会为上传到该存储分区的所有对象分配该默认存储类别。

      注意:右侧窗格中的每月费用估算面板会根据您选择的存储类别和位置以及您预期的数据大小和操作,估算存储分区的每月费用。

    • 对于选择如何控制对象的访问权限,请选择您的存储分区是否强制执行禁止公开访问,然后选择存储分区对象的访问权限控制模型

      注意:如果项目的组织政策已实施禁止公开访问,则禁止公开访问切换开关处于锁定状态。

    • 对于选择如何保护对象数据,请根据需要配置 **保护工具**,然后选择 **数据加密** 方法
  4. 点击创建

如需了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息,请参阅问题排查

gsutil

使用 gsutil mb 命令:

gsutil mb gs://BUCKET_NAME

其中:

  • BUCKET_NAME 是您要为自己的存储分区指定的名称(须遵循命名要求),例如 my-bucket

如果请求成功,该命令将返回以下消息:

Creating gs://BUCKET_NAME/...

设置以下可选标志,以便更好地控制存储分区的创建:

  • -p:指定将与您的存储桶相关联的项目 ID 或项目编号,例如 my-project
  • -c:指定存储分区的默认存储类别,例如 NEARLINE
  • -l:指定存储分区的位置,例如 US-EAST1
  • -b:为存储分区启用统一存储分区级访问权限

例如:

  gsutil mb -p PROJECT_ID -c STORAGE_CLASS -l BUCKET_LOCATION -b on gs://BUCKET_NAME

代码示例

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& storage_class, std::string const& location) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.CreateBucket(bucket_name, gcs::BucketMetadata()
                                           .set_storage_class(storage_class)
                                           .set_location(location));

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

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

C#

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


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

public class CreateRegionalBucketSample
{
    /// <summary>
    /// Creates a storage bucket with region.
    /// </summary>
    /// <param name="projectId">The ID of the project to create the buckets in.</param>
    /// <param name="location">The location of the bucket. Object data for objects in the bucket resides in
    /// physical storage within this region. Defaults to US.</param>
    /// <param name="bucketName">The name of the bucket to create.</param>
    /// <param name="storageClass">The bucket's default storage class, used whenever no storageClass is specified
    /// for a newly-created object. This defines how objects in the bucket are stored
    /// and determines the SLA and the cost of storage. Values include MULTI_REGIONAL,
    /// REGIONAL, STANDARD, NEARLINE, COLDLINE, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY.
    /// If this value is not specified when the bucket is created, it will default to
    /// STANDARD.</param>
    public Bucket CreateRegionalBucket(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string location = "us-west1",
        string storageClass = "REGIONAL")
    {
        var storage = StorageClient.Create();
        Bucket bucket = new Bucket
        {
            Location = location,
            Name = bucketName,
            StorageClass = storageClass
        };
        var newlyCreatedBucket = storage.CreateBucket(projectId, bucket);
        Console.WriteLine($"Created {bucketName}.");
        return newlyCreatedBucket;
    }
}

Go

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

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

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

// createBucketClassLocation creates a new bucket in the project with Storage class and
// location.
func createBucketClassLocation(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	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()

	storageClassAndLocation := &storage.BucketAttrs{
		StorageClass: "COLDLINE",
		Location:     "asia",
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, storageClassAndLocation); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v in %v with storage class %v\n", bucketName, storageClassAndLocation.Location, storageClassAndLocation.StorageClass)
	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.StorageClass;
import com.google.cloud.storage.StorageOptions;

public class CreateBucketWithStorageClassAndLocation {
  public static void createBucketWithStorageClassAndLocation(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

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

    // See the StorageClass documentation for other valid storage classes:
    // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
    StorageClass storageClass = StorageClass.COLDLINE;

    // See this documentation for other valid locations:
    // http://g.co/cloud/storage/docs/bucket-locations#location-mr
    String location = "ASIA";

    Bucket bucket =
        storage.create(
            BucketInfo.newBuilder(bucketName)
                .setStorageClass(storageClass)
                .setLocation(location)
                .build());

    System.out.println(
        "Created bucket "
            + bucket.getName()
            + " in "
            + bucket.getLocation()
            + " with storage class "
            + bucket.getStorageClass());
  }
}

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 name of a storage class
// See the StorageClass documentation for other valid storage classes:
// https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
// const storageClass = 'coldline';

// The name of a location
// See this documentation for other valid locations:
// http://g.co/cloud/storage/docs/bucket-locations#location-mr
// const location = 'ASIA';

// 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 createBucketWithStorageClassAndLocation() {
  // For default values see: https://cloud.google.com/storage/docs/locations and
  // https://cloud.google.com/storage/docs/storage-classes
  const [bucket] = await storage.createBucket(bucketName, {
    location,
    [storageClass]: true,
  });

  console.log(
    `${bucket.name} created with ${storageClass} class in ${location}`
  );
}

createBucketWithStorageClassAndLocation().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.
 */
function create_bucket_class_location($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $storageClass = 'COLDLINE';
    $location = 'ASIA';
    $bucket = $storage->createBucket($bucketName, [
        'storageClass' => $storageClass,
        'location' => $location,
    ]);

    $objects = $bucket->objects([
        'encryption' => [
            'defaultKmsKeyName' => null,
        ]
    ]);

    printf('Created bucket %s in %s with storage class %s', $bucketName, $storageClass, $location);
}

Python

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

from google.cloud import storage

def create_bucket_class_location(bucket_name):
    """Create a new bucket in specific location with storage class"""
    # bucket_name = "your-new-bucket-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    bucket.storage_class = "COLDLINE"
    new_bucket = storage_client.create_bucket(bucket, location="us")

    print(
        "Created bucket {} in {} with storage class {}".format(
            new_bucket.name, new_bucket.location, new_bucket.storage_class
        )
    )
    return new_bucket

Ruby

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

def create_bucket_class_location bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.create_bucket bucket_name,
                                  location:      "ASIA",
                                  storage_class: "COLDLINE"

  puts "Created bucket #{bucket.name} in #{bucket.location} with #{bucket.storage_class} class"
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。 如需了解相关说明,请参阅 API 身份验证
  2. 创建一个包含存储分区设置的 .json 文件,其中必须包含存储分区的 name。如需查看完整的设置列表,请参阅存储分区:插入文档。以下是一些常用的设置,包括:
  3. {
      "name": "BUCKET_NAME",
      "location": "BUCKET_LOCATION",
      "storageClass": "STORAGE_CLASS",
      "iamConfiguration": {
        "uniformBucketLevelAccess": {
          "enabled": true
        },
      }
    }

    其中:

    • BUCKET_NAME 是您要为自己的存储分区指定的名称(须遵循命名要求),例如 my-bucket
    • BUCKET_LOCATION 是您要用于存储自己的存储分区对象数据位置,例如 US-EAST1
    • STORAGE_CLASS 是您存储分区的默认存储类别,例如 NEARLINE
  4. 使用 cURL 调用 JSON API
    curl -X POST --data-binary @JSON_FILE_NAME.json \
         -H "Authorization: Bearer OAUTH2_TOKEN" \
         -H "Content-Type: application/json" \
         "https://storage.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的 JSON 文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • PROJECT_IDENTIFIER 是将与您的存储桶相关联的项目的 ID 或编号,例如 my-project

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。 如需了解相关说明,请参阅 API 身份验证
  2. 创建一个包含以下信息的 .xml 文件:
  3. <CreateBucketConfiguration>
       <LocationConstraint>BUCKET_LOCATION</LocationConstraint>
       <StorageClass>STORAGE_CLASS</StorageClass>
    </CreateBucketConfiguration>

    其中:

    • BUCKET_LOCATION 是您要用于存储自己的存储分区对象数据位置,例如 US-EAST1
    • STORAGE_CLASS 是您存储分区的默认存储类别,例如 NEARLINE
  4. 使用 cURL 调用 XML API
    curl -X PUT --data-binary @XML_FILE_NAME.xml \
         -H "Authorization: Bearer OAUTH2_TOKEN" \
         -H "x-goog-project-id: PROJECT_ID" \
         "https://storage.googleapis.com/BUCKET_NAME"

    其中:

    • XML_FILE_NAME 是您在第 2 步中创建的 XML 文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • PROJECT_ID 是将与您的存储分区相关联的项目的 ID,例如 my-project
    • BUCKET_NAME 是您要为自己的存储分区指定的名称(须遵循命名要求),例如 my-bucket

后续步骤

自行试用

如果您是 Google Cloud 新手,请创建一个帐号来评估 Cloud Storage 在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。

免费试用 Cloud Storage