更改存储分区的默认存储类别

本页面介绍如何更改存储分区的默认存储类别。将对象上传到存储分区时,如果您没有指定对象的存储类别,则系统会为该对象分配存储分区的默认存储类别。如需查看存储分区的概览,请参阅关键术语。如需详细了解存储类别,请参阅存储类别

要更改现有存储分区的默认存储类别,请按如下所述操作:

控制台

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

    转到浏览器

  2. 在存储分区列表中,找到要修改的存储分区,然后点击其存储分区溢出 (Bucket overflow) 菜单 ()。

  3. 点击修改默认存储类别

  4. 在重叠式窗口中,为您的存储分区选择所需的新默认存储类别。

  5. 点击保存

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

gsutil

使用 gsutil defstorageclass set 命令:

gsutil defstorageclass set STORAGE_CLASS gs://BUCKET_NAME

其中:

  • STORAGE_CLASS 是您想要用于存储分区的新存储类别,例如 nearline
  • BUCKET_NAME 是相关存储分区的名称, 例如 my-bucket

响应类似如下示例:

Setting default storage class to "nearline" for bucket gs://my-bucket

代码示例

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) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);

  if (!original) throw std::runtime_error(original.status().message());
  gcs::BucketMetadata desired = *original;
  desired.set_storage_class(storage_class);

  StatusOr<gcs::BucketMetadata> patched =
      client.PatchBucket(bucket_name, *original, desired);

  if (!patched) throw std::runtime_error(patched.status().message());
  std::cout << "Storage class for bucket " << patched->name()
            << " has been patched to " << patched->storage_class() << "."
            << "\nFull metadata: " << *patched << "\n";
}

C#

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


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

public class ChangeDefaultStorageClassSample
{
	public Bucket ChangeDefaultStorageClass(string bucketName = "your-bucket-name", string storageClass = StorageClasses.Standard)
	{
	    var storage = StorageClient.Create();
	    var bucket = storage.GetBucket(bucketName);

	    bucket.StorageClass = storageClass;

	    bucket = storage.UpdateBucket(bucket);
	    Console.WriteLine($"Default storage class for bucket {bucketName} changed to {storageClass}.");
	    return bucket;
	}
}

Go

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

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

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

// changeDefaultStorageClass changes the storage class on a bucket.
func changeDefaultStorageClass(w io.Writer, bucketName string) error {
	// 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()

	bucket := client.Bucket(bucketName)
	newStorageClass := "COLDLINE"
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		StorageClass: newStorageClass,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Default storage class for bucket %v has been set to %v\n", bucketName, newStorageClass)
	return nil
}

Java

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

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

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

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

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    bucket = bucket.toBuilder().setStorageClass(storageClass).build().update();

    System.out.println(
        "Default storage class for bucket "
            + bucketName
            + " has been set to "
            + 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';

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

// Creates a client
const storage = new Storage();

async function changeDefaultStorageClass() {
  await storage.bucket(bucketName).setStorageClass(storageClass);

  console.log(`${bucketName} has been set to ${storageClass}`);
}

changeDefaultStorageClass().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Change the default storage class for the given bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 */
function change_default_storage_class($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $storageClass = 'COLDLINE';

    $bucket->update([
        'storageClass' => $storageClass,
    ]);

    printf(
        'Default storage class for bucket %s has been set to %s',
        $bucketName,
        $storageClass
    );
}

Python

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

from google.cloud import storage
from google.cloud.storage import constants

def change_default_storage_class(bucket_name):
    """Change the default storage class of the bucket"""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.storage_class = constants.COLDLINE_STORAGE_CLASS
    bucket.patch()

    print("Default storage class for bucket {} has been set to {}".format(bucket_name, bucket.storage_class))
    return bucket

Ruby

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

def change_default_storage_class bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  bucket.storage_class = "COLDLINE"

  puts "Default storage class for bucket #{bucket_name} has been set to #{bucket.storage_class}"
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "storageClass": "STORAGE_CLASS"
    }

    其中 STORAGE_CLASS 是您想要用于存储分区的新存储类别,例如 nearline

  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API

    curl -X PATCH --data-binary @JSON_FILE_NAME.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=storageClass"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的 JSON 文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .xml 文件:

    <StorageClass>STORAGE_CLASS</StorageClass>

    其中 STORAGE_CLASS 是您想要用于存储分区的新存储类别的名称,例如 nearline

  3. 使用 cURL,通过 PUT Bucket 请求调用 XML API

    curl -X PUT --data-binary @XML_FILE_NAME.xml \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?storageClass"

    其中:

    • XML_FILE_NAME 是您在第 2 步中创建的 XML 文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

后续步骤