建立及管理執行個體

本頁面說明如何建立、列出、編輯及刪除 Spanner 執行個體。

建立執行個體

您可以使用 Google Cloud 控制台、Google Cloud CLI 或用戶端程式庫建立執行個體。您也可以新增選用的唯讀副本,使用自訂執行個體設定建立執行個體。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

  2. 點選「建立執行個體」。

    前往「Create instance」(建立執行個體) 頁面

  3. 在「Select an edition」(選取版本) 區段中,選取 Spanner 版本。

    如要比較不同版本的規格,請按一下「Compare editions」(比較版本)。詳情請參閱「Spanner 版本總覽」。

  4. 按一下「繼續」。

  5. 在「Name your instance」(命名執行個體) 區段中,輸入要在 Google Cloud 控制台顯示的「Instance name」(執行個體名稱)。執行個體名稱不得與 Google Cloud 專案中的其他名稱重複。

  6. 輸入執行個體 ID,永久識別執行個體。執行個體 ID 在 Google Cloud 專案中也必須是唯一的。執行個體 ID 設定後即無法變更。

  7. 按一下「繼續」。

  8. 在「Configure your instance」(設定執行個體) 區段的「Choose a configuration」(選擇設定) 下方,選取「Regional」(區域)、「Dual-region」(雙區域) 或「Multi-region」(多區域)。

  9. 從下拉式選單中選取設定位置。

  10. 選用:如要將唯讀副本新增至 Spanner 基礎設定,請先使用 gcloud CLI 建立自訂執行個體設定。Enterprise 版和 Enterprise Plus 版可將選用的唯讀副本新增至基本設定。

  11. 按一下「繼續」。

  12. 在「Allocate compute capacity」(分配運算能力) 區段的「Select unit」(選取單位) 下方,點選下列其中一個選項:

    • 節點:適用於大型執行個體。1 個節點等於 1,000 個處理單元。
    • 小型執行個體的處理單元。

    詳情請參閱「運算資源、節點和處理單元」。

  13. 在「Choose a scaling mode」(選擇資源調度模式) 下方,按一下下列其中一個選項:

    • 如要手動設定運算能力,以使用定量的運算資源並支付固定費用,請選取「手動分配」。

      • Quantity:指出這個執行個體要使用的處理單元或節點數量。
    • 自動調度資源:讓 Spanner 自動增減運算能力。代管自動配置器適用於 Spanner Enterprise 版和 Enterprise Plus 版。如要進一步瞭解代管自動配置器,請參閱「Spanner 代管自動配置器」。設定下列代管自動配置器選項:

      • 「Minimum」(最小值) 表示縮減資源的下限,具體取決於您為「Compute capacity」(運算能力) 選擇的測量單位。詳情請參閱「判斷最低限制」。
      • 「Maximum」(最大值) 表示可擴充的最大限制,具體取決於您為「Compute capacity」(運算能力) 選擇的測量單位。詳情請參閱「判斷上限」。
      • 「高優先順序 CPU 使用率目標」是指高優先順序工作要使用的 CPU 目標百分比。詳情請參閱「決定 CPU 使用率目標」。
      • 「Total CPU utilization target」(CPU 總使用率目標):所有低、中、高優先順序工作的 CPU 使用率目標百分比。詳情請參閱「決定 CPU 總使用率目標」。
      • 「Storage utilization target」(儲存空間使用率目標) 是指要使用的儲存空間目標百分比。詳情請參閱「決定儲存空間使用率目標」。
  14. 選用:如果選取「Autoscaling」(自動調度資源) 做為調度資源模式,可以點選「Show asymmetric autoscaling options」(顯示非對稱自動調度資源選項) 下拉式選單,自動調度唯讀副本的資源,不受其他副本影響。詳情請參閱「非對稱唯讀自動調整資源配置」。

    1. 選取要非對稱自動調度資源的唯讀副本。

    2. 設定下列非對稱自動配置器選項:

      • 「Minimum」(最小值) 表示縮減資源的下限,具體取決於您為「Compute capacity」(運算能力) 選擇的測量單位。詳情請參閱「判斷最低限制」。
      • 「Maximum」(最大值) 表示可擴充的最大限制,具體取決於您為「Compute capacity」(運算能力) 選擇的測量單位。詳情請參閱「判斷上限」。
      • 高優先順序 CPU 使用率目標:高優先順序工作的 CPU 使用率目標百分比。詳情請參閱「決定高優先順序 CPU 使用率目標」。
      • 「Total CPU utilization target」(CPU 總使用率目標) 表示所有低、中、高優先順序工作的 CPU 使用率目標百分比。CPU 百分比可以介於 10% 到 90% 之間。總 CPU 目標必須大於高優先順序 CPU 目標。如要盡可能降低成本,請使用較高的百分比。詳情請參閱「決定 CPU 總使用率目標」。
      • 「Disable total CPU」(停用總 CPU) 表示自動配置器應明確忽略總 CPU 目標。
      • 停用高優先順序 CPU:表示自動配置器應明確忽略高優先順序工作的 CPU 目標。
  15. 在「Backups」(備份) 下方,系統預設會勾選「Enable default backup schedules」(啟用預設備份排程) 核取方塊。如要停用預設備份排程,請取消勾選核取方塊。啟用後,執行個體中的所有新資料庫都會每 24 小時建立完整備份。備份會保留 7 天。 您隨時可以編輯或刪除預設備份排程。詳情請參閱「預設備份排程」。

  16. 按一下「建立」,建立執行個體。

gcloud

使用 gcloud spanner instances create 指令建立執行個體。指定運算能力,也就是執行個體所需的節點或處理單元數量。

gcloud spanner instances create INSTANCE_ID \
--edition=EDITION \
--config=INSTANCE_CONFIG \
--description=INSTANCE_DESCRIPTION \
--default-backup-schedule-type=DEFAULT_BACKUP_SCHEDULE_TYPE \
--nodes=NODE_COUNT

或

gcloud spanner instances create INSTANCE_ID \
--edition=EDITION \
--config=INSTANCE_CONFIG \
--description=INSTANCE_DESCRIPTION \
--default-backup-schedule-type=DEFAULT_BACKUP_SCHEDULE_TYPE \
--processing-units=PROCESSING_UNIT_COUNT

更改下列內容:

  • INSTANCE-ID: Google Cloud 專案中不重複的永久 ID。執行個體 ID 設定後即無法變更。
  • INSTANCE-CONFIG:執行個體設定的永久 ID,用於定義執行個體的地理位置,並影響資料複製方式。自訂執行個體設定則是以 custom- 開頭。詳情請參閱「執行個體設定」。
  • INSTANCE_DESCRIPTION: Google Cloud 控制台中顯示的執行個體名稱。執行個體名稱在Google Cloud 專案中不得重複。
  • DEFAULT_BACKUP_SCHEDULE_TYPE:執行個體使用的預設備份排程類型。必須是下列其中一個值:

    • AUTOMATIC:在執行個體中建立新資料庫時,系統會自動建立預設備份排程。預設備份排程每 24 小時會建立完整備份。這些完整備份會保留 7 天。建立預設備份排程後,您可以編輯或刪除。
    • NONE:在執行個體中建立新的資料庫時,系統不會自動建立預設備份排程。
  • NODE-COUNT:執行個體的運算能力,以節點數量表示。每個節點等於 1,000 個處理單元。

  • PROCESSING_UNIT_COUNT:執行個體的運算資源,以處理單元數量表示。1,000 以下的數量請以 100 的倍數輸入 (100、200、300 等),超過 1,000 的數量則以 1,000 的倍數輸入 (1,000、2,000、3,000 等)。注意:如果您建立的執行個體日後要啟用代管自動配置器,請勿使用這個參數。

新增代管式自動調度資源

您也可以建立 Enterprise 版和 Enterprise Plus 版執行個體,使用 gcloud spanner instances create 指令啟用代管自動調度資源功能。詳情請參閱「Spanner 代管自動配置器」。

使用下列指令,建立具有代管自動配置器的執行個體。

  gcloud spanner instances create INSTANCE_ID \
    --edition=EDITION \
    --config=INSTANCE_CONFIG \
    --description=INSTANCE_DESCRIPTION \
    --autoscaling-min-processing-units=MINIMUM_PROCESSING_UNITS \
    --autoscaling-max-processing-units=MAXIMUM_PROCESSING_UNITS \
    --autoscaling-high-priority-cpu-target=HIGH_PRIORITY_CPU_PERCENTAGE \
    --autoscaling-total-cpu-target=TOTAL_CPU_PERCENTAGE \
    --autoscaling-storage-target=STORAGE_PERCENTAGE \
    [--disable-downscaling | --no-disable-downscaling] \
    [--asymmetric-autoscaling-option \
       location=ASYMMETRIC_AUTOSCALING_LOCATION,\
       min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\
       max_nodes=ASYMMETRIC_AUTOSCALING_MAX,\
       high_priority_cpu_target=ASYMMETRIC_HIGH_PRIORITY_CPU_TARGET,\
       total_cpu_target=ASYMMETRIC_TOTAL_CPU_TARGET \
       [,disable_total_cpu_autoscaling=TRUE|FALSE \
       | disable_high_priority_cpu_autoscaling=TRUE|FALSE]
    ]

或

  gcloud spanner instances create INSTANCE_ID \
    --edition=EDITION \
    --config=INSTANCE_CONFIG \
    --description=INSTANCE_DESCRIPTION \
    --autoscaling-min-nodes=MINIMUM_NODES \
    --autoscaling-max-nodes=MAXIMUM_NODES \
    --autoscaling-high-priority-cpu-target=HIGH_PRIORITY_CPU_PERCENTAGE \
    --autoscaling-total-cpu-target=TOTAL_CPU_PERCENTAGE \
    --autoscaling-storage-target=STORAGE_PERCENTAGE \
    [--disable-downscaling | --no-disable-downscaling] \
    [--asymmetric-autoscaling-option \
       location=ASYMMETRIC_AUTOSCALING_LOCATION,\
       min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\
       max_nodes=ASYMMETRIC_AUTOSCALING_MAX,\
       high_priority_cpu_target=ASYMMETRIC_HIGH_PRIORITY_CPU_TARGET, \
       total_cpu_target=ASYMMETRIC_TOTAL_CPU_TARGET, \
       [,disable_total_cpu_autoscaling=TRUE|FALSE \
       | disable_high_priority_cpu_autoscaling=TRUE|FALSE]
    ]

更改下列內容:

  • INSTANCE-ID: Google Cloud 專案中不重複的永久 ID。執行個體 ID 設定後即無法變更。
  • INSTANCE-CONFIG:執行個體設定的永久 ID,用於定義執行個體的地理位置,並影響資料複製方式。自訂執行個體設定則是以 custom- 開頭。詳情請參閱「執行個體設定」。
  • INSTANCE-DESCRIPTION: Google Cloud 控制台中顯示的執行個體名稱。執行個體名稱在Google Cloud 專案中不得重複。
  • MINIMUM_PROCESSING_UNITS、MINIMUM_NODES:縮減時的處理單元或節點數量下限。詳情請參閱「判斷最低限制」。
  • MAXIMUM_PROCESSING_UNITS、MAXIMUM_NODES:向上擴充時的處理單元或節點數量上限。詳情請參閱「判斷上限」。
  • HIGH_PRIORITY_CPU_PERCENTAGE:根據工作優先順序,設定高優先順序 CPU 的目標使用率。CPU 百分比可以介於 10% 到 90% 之間。如要盡可能降低成本,請使用較高的百分比。詳情請參閱「決定高優先順序 CPU 使用率目標」。
  • TOTAL_CPU_PERCENTAGE:要使用的優先 CPU 總量目標百分比。總 CPU 目標必須大於高優先順序 CPU 目標。CPU 百分比可以介於 10% 到 90% 之間。如要盡可能降低費用,請使用較高的百分比。詳情請參閱「決定 CPU 總使用率目標」。
  • STORAGE_PERCENTAGE:儲存空間使用率目標百分比,範圍為 10% 到 99%。詳情請參閱「決定儲存空間使用率目標」。

選用標記:

  • --disable-downscaling:使用這個布林值旗標停用縮減功能。如果設為 TRUE,自動配置器就不會減少節點或處理單元數量。向上調度功能會繼續正常運作,以因應增加的需求。如要在停用後啟用縮減功能,請使用 --no-disable-downscaling 旗標。
  • --asymmetric-autoscaling-option:使用這個旗標啟用非對稱自動調度資源。替換下列參數:

    • ASYMMETRIC_AUTOSCALING_LOCATION:如果使用旗標,則必須提供這個參數。要以非對稱方式調度資源的唯讀區域位置。
    • ASYMMETRIC_AUTOSCALING_MIN:選用參數。縮減時的節點數量下限。如未指定,這個值會沿用基礎執行個體設定。
    • ASYMMETRIC_AUTOSCALING_MAX:選用參數。向上擴充時的節點數量上限。如未指定,這個值會沿用基礎執行個體設定。
    • ASYMMETRIC_HIGH_PRIORITY_CPU_TARGET:選用參數。根據工作優先順序,設定要使用的 CPU 目標百分比。如未指定,這個值會沿用基礎執行個體設定。如果想盡可能降低成本,請使用較高的百分比。副本的目標百分比可以與基本執行個體和其他副本不同,但如果是容錯移轉情境,建議副本在不同副本之間使用一致的目標。詳情請參閱「容錯移轉相關問題」。
    • ASYMMETRIC_TOTAL_CPU_TARGET:選用參數。將總 CPU 的目標設為 10% 到 90%。如未指定,這個值會沿用基礎執行個體設定。如果想盡可能降低成本,請使用較高的百分比。副本的目標百分比可以與基本執行個體和其他副本不同,但如果是容錯移轉情境,建議副本在不同副本之間使用一致的目標。詳情請參閱「非對稱自動調度唯讀資源」。
    • disable_total_cpu_autoscaling:如果您不希望自動配置器自動調度副本的總 CPU 資源,請將這個參數設為 TRUE。如要讓執行個體從基本執行個體繼承 total_cpu_autoscaling 目標,請勿指定這個參數。您無法在同一個副本上同時停用 CPU 總用量和高優先順序 CPU。
    • disable_high_priority_cpu_autoscaling:如果不希望自動配置器自動調度副本的高優先順序 CPU 資源,請將 disable_high_priority_cpu_autoscaling 設為 TRUE。如要讓執行個體從基本執行個體繼承 high_priority_cpu_autoscaling 目標,請勿指定這個參數。您無法在同一個副本上同時停用總 CPU 和高優先順序 CPU。

使用自訂設定的範例

如要在基本區域執行個體設定 us-central1 中建立執行個體 test-instance,請執行:

gcloud spanner instances create test-instance --edition=STANDARD --config=regional-us-central1 \
  --description="Test Instance" --nodes=1

如要在自訂多區域執行個體設定 custom-eur6 中建立執行個體 custom-eur6-instance,請先建立自訂執行個體設定。

接著,執行以下指令:

  gcloud spanner instances create custom-eur6-instance --edition=ENTERPRISE_PLUS --config=custom-eur6 \
      --description="Instance with custom read-only" --nodes=1

執行上述任一指令後,您應該會看到類似下列範例的訊息:

Creating instance...done.

C++

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

void CreateInstance(google::cloud::spanner_admin::InstanceAdminClient client,
                    std::string const& project_id,
                    std::string const& instance_id,
                    std::string const& display_name,
                    std::string const& config_id) {
  namespace spanner = ::google::cloud::spanner;
  spanner::Instance in(project_id, instance_id);

  auto project = google::cloud::Project(project_id);
  std::string config_name =
      project.FullName() + "/instanceConfigs/" + config_id;
  auto instance =
      client
          .CreateInstance(spanner::CreateInstanceRequestBuilder(in, config_name)
                              .SetDisplayName(display_name)
                              .SetNodeCount(1)
                              .SetLabels({{"cloud_spanner_samples", "true"}})
                              .Build())
          .get();
  if (!instance) throw std::move(instance).status();
  std::cout << "Created instance [" << in << "]:\n" << instance->DebugString();
}

C#

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.LongRunning;
using System;
using System.Threading.Tasks;

public class CreateInstanceAsyncSample
{
    public async Task<Instance> CreateInstanceAsync(
        string projectId,
        string instanceId,
        Instance.Types.Edition edition = Instance.Types.Edition.Standard)
    {
        // Create the InstanceAdminClient instance.
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();

        // Initialize request parameters.
        Instance instance = new Instance
        {
            InstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig(projectId, "regional-us-central1"),
            DisplayName = "This is a display name.",
            NodeCount = 1,
            Labels =
            {
                { "cloud_spanner_samples", "true" },
            },
            Edition = edition,
        };
        ProjectName projectName = ProjectName.FromProject(projectId);

        // Make the CreateInstance request.
        Operation<Instance, CreateInstanceMetadata> response = await instanceAdminClient.CreateInstanceAsync(projectName, instanceId, instance);

        Console.WriteLine("Waiting for the operation to finish.");

        // Poll until the returned long-running operation is complete.
        Operation<Instance, CreateInstanceMetadata> completedResponse = await response.PollUntilCompletedAsync();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Error while creating instance: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        Console.WriteLine($"Instance created successfully.");

        return completedResponse.Result;
    }
}

建立不含預設備份排程的執行個體


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.LongRunning;
using System;
using System.Threading.Tasks;

public class CreateInstanceWithoutDefaultBackupSchedulesAsyncSample
{
    public async Task<Instance> CreateInstanceWithoutDefaultBackupSchedulesAsync(string projectId, string instanceId)
    {
        // Create the InstanceAdminClient instance.
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();

        // Initialize request parameters.
        Instance instance = new Instance
        {
            InstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            ConfigAsInstanceConfigName =
                InstanceConfigName.FromProjectInstanceConfig(projectId, "regional-me-central2"),
            DisplayName = "This is a display name.",
            NodeCount = 1,
            Labels =
            {
                { "cloud_spanner_samples", "true" },
            },
            DefaultBackupScheduleType = Instance.Types.DefaultBackupScheduleType.None,
        };
        ProjectName projectName = ProjectName.FromProject(projectId);

        // Make the CreateInstance request.
        Operation<Instance, CreateInstanceMetadata> response =
            await instanceAdminClient.CreateInstanceAsync(projectName, instanceId, instance);

        Console.WriteLine("Waiting for the operation to finish.");

        // Poll until the returned long-running operation is complete.
        Operation<Instance, CreateInstanceMetadata> completedResponse =
            await response.PollUntilCompletedAsync();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Error while creating instance: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        Console.WriteLine($"Instance created successfully.");
        return completedResponse.Result;
    }
}

Go

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

func createInstance(w io.Writer, projectID, instanceID string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance"
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	op, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{
		Parent:     fmt.Sprintf("projects/%s", projectID),
		InstanceId: instanceID,
		Instance: &instancepb.Instance{
			Config:      fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, "regional-us-central1"),
			DisplayName: instanceID,
			NodeCount:   1,
			Labels:      map[string]string{"cloud_spanner_samples": "true"},
			Edition:     instancepb.Instance_STANDARD,
		},
	})
	if err != nil {
		return fmt.Errorf("could not create instance %s: %w", fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID), err)
	}
	// Wait for the instance creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance creation to finish failed: %w", err)
	}
	// The instance may not be ready to serve yet.
	if i.State != instancepb.Instance_READY {
		fmt.Fprintf(w, "instance state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Created instance [%s]\n", instanceID)
	return nil
}

使用 Go 建立具備代管自動調度資源功能的執行個體

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// Example of creating an autoscaling instance with Go.
// projectID is the ID of the project that the new instance will be in.
// instanceID is the ID of the new instance to be created.
func createInstanceWithAutoscalingConfig(w io.Writer, projectID, instanceID string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance"
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return fmt.Errorf("could not create instance admin client for project %s: %w", projectID, err)
	}
	defer instanceAdmin.Close()

	instanceName := fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID)
	fmt.Fprintf(w, "Creating instance %s.", instanceName)

	op, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{
		Parent:     fmt.Sprintf("projects/%s", projectID),
		InstanceId: instanceID,
		Instance: &instancepb.Instance{
			Config:      fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, "regional-us-central1"),
			DisplayName: "Create instance example",
			AutoscalingConfig: &instancepb.AutoscalingConfig{
				AutoscalingLimits: &instancepb.AutoscalingConfig_AutoscalingLimits{
					MinLimit: &instancepb.AutoscalingConfig_AutoscalingLimits_MinNodes{
						MinNodes: 1,
					},
					MaxLimit: &instancepb.AutoscalingConfig_AutoscalingLimits_MaxNodes{
						MaxNodes: 2,
					},
				},
				AutoscalingTargets: &instancepb.AutoscalingConfig_AutoscalingTargets{
					HighPriorityCpuUtilizationPercent: 65,
					StorageUtilizationPercent:         95,
				},
			},
			Labels:  map[string]string{"cloud_spanner_samples": "true"},
			Edition: instancepb.Instance_ENTERPRISE_PLUS,
		},
	})
	if err != nil {
		return fmt.Errorf("could not create instance %s: %w", instanceName, err)
	}
	fmt.Fprintf(w, "Waiting for operation on %s to complete...", instanceID)
	// Wait for the instance creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance creation to finish failed: %w", err)
	}
	// The instance may not be ready to serve yet.
	if i.State != instancepb.Instance_READY {
		fmt.Fprintf(w, "instance state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Created instance [%s].\n", instanceID)

	instance, err := instanceAdmin.GetInstance(ctx, &instancepb.GetInstanceRequest{
		Name: instanceName,
		// Get the autoscaling_config field from the newly created instance.
		FieldMask: &field_mask.FieldMask{Paths: []string{"autoscaling_config"}},
	})
	if err != nil {
		return fmt.Errorf("failed to get instance [%s]: %w", instanceName, err)
	}
	fmt.Fprintf(w, "Instance %s has autoscaling_config: %s.", instanceID, instance.AutoscalingConfig)
	return nil
}

使用 Go 建立具備非對稱自動調度唯讀資源功能的執行個體

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// createInstanceWithAsymmetricAutoscalingConfig is a code snippet to show
// an example of creating an asymmetric autoscaling enabled instance in Go.
//
// projectID is the ID of the project that the new instance will be in.
// instanceID is the ID of the new instance to be created.
func createInstanceWithAsymmetricAutoscalingConfig(w io.Writer, projectID, instanceID string) error {
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return fmt.Errorf("could not create instance admin client for project %s: %w", projectID, err)
	}
	defer instanceAdmin.Close()

	instanceName := fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID)
	fmt.Fprintf(w, "Creating instance %s.", instanceName)

	op, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{
		Parent:     fmt.Sprintf("projects/%s", projectID),
		InstanceId: instanceID,
		Instance: &instancepb.Instance{
			Config:      fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, "nam-eur-asia3"),
			DisplayName: "Create instance example",
			AutoscalingConfig: &instancepb.AutoscalingConfig{
				AutoscalingLimits: &instancepb.AutoscalingConfig_AutoscalingLimits{
					MinLimit: &instancepb.AutoscalingConfig_AutoscalingLimits_MinNodes{
						MinNodes: 1,
					},
					MaxLimit: &instancepb.AutoscalingConfig_AutoscalingLimits_MaxNodes{
						MaxNodes: 10,
					},
				},
				AutoscalingTargets: &instancepb.AutoscalingConfig_AutoscalingTargets{
					HighPriorityCpuUtilizationPercent: 65,
					StorageUtilizationPercent:         95,
				},
				// Read-only replicas in europe-west1, europe-west4, and asia-east1 are autoscaled
				// independly from other replicas based on the usage in the respective region.
				AsymmetricAutoscalingOptions: []*instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{
					&instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{
						ReplicaSelection: &instancepb.ReplicaSelection{
							Location: "europe-west1",
						},
					},
					&instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{
						ReplicaSelection: &instancepb.ReplicaSelection{
							Location: "europe-west4",
						},
					},
					&instancepb.AutoscalingConfig_AsymmetricAutoscalingOption{
						ReplicaSelection: &instancepb.ReplicaSelection{
							Location: "asia-east1",
						},
					},
				},
			},
			Labels:  map[string]string{"cloud_spanner_samples": "true"},
			Edition: instancepb.Instance_ENTERPRISE_PLUS,
		},
	})
	if err != nil {
		return fmt.Errorf("could not create instance %s: %w", instanceName, err)
	}
	fmt.Fprintf(w, "Waiting for operation on %s to complete...", instanceID)
	// Wait for the instance creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance creation to finish failed: %w", err)
	}
	// The instance may not be ready to serve yet.
	if i.State != instancepb.Instance_READY {
		fmt.Fprintf(w, "instance state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Created instance [%s].\n", instanceID)

	instance, err := instanceAdmin.GetInstance(ctx, &instancepb.GetInstanceRequest{
		Name: instanceName,
		// Get the autoscaling_config field from the newly created instance.
		FieldMask: &field_mask.FieldMask{Paths: []string{"autoscaling_config"}},
	})
	if err != nil {
		return fmt.Errorf("failed to get instance [%s]: %w", instanceName, err)
	}
	fmt.Fprintf(w, "Instance %s has autoscaling_config: %s.", instanceID, instance.AutoscalingConfig)
	return nil
}

建立不含預設備份排程的執行個體

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// createInstanceWithoutDefaultBackupSchedule creates instance with default backup schedule disabled.
func createInstanceWithoutDefaultBackupSchedule(w io.Writer, projectID, instanceID string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance"
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	// Create an instance without default backup schedule, whicn means no default backup schedule will
	// be created automatically on creation of a database within the instance.
	req := &instancepb.CreateInstanceRequest{
		Parent:     fmt.Sprintf("projects/%s", projectID),
		InstanceId: instanceID,
		Instance: &instancepb.Instance{
			Config:                    fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, "regional-us-central1"),
			DisplayName:               instanceID,
			NodeCount:                 1,
			Labels:                    map[string]string{"cloud_spanner_samples": "true"},
			DefaultBackupScheduleType: instancepb.Instance_NONE,
		},
	}

	op, err := instanceAdmin.CreateInstance(ctx, req)
	if err != nil {
		return fmt.Errorf("could not create instance %s: %w", fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID), err)
	}
	// Wait for the instance creation to finish.  For more information about instances, see
	// https://cloud.google.com/spanner/docs/instances.
	instance, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance creation to finish failed: %w", err)
	}
	// The instance may not be ready to serve yet.
	if instance.State != instancepb.Instance_READY {
		fmt.Fprintf(w, "instance state is not READY yet. Got state %v\n", instance.State)
	}
	fmt.Fprintf(w, "Created instance [%s]\n", instanceID)
	return nil
}

Java

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.CreateInstanceRequest;
import com.google.spanner.admin.instance.v1.Instance;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.ProjectName;
import java.util.concurrent.ExecutionException;

class CreateInstanceExample {

  static void createInstance() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    createInstance(projectId, instanceId);
  }

  static void createInstance(String projectId, String instanceId) {
    // Set Instance configuration.
    int nodeCount = 2;
    String displayName = "Descriptive name";

    // Create an Instance object that will be used to create the instance.
    Instance instance =
        Instance.newBuilder()
            .setDisplayName(displayName)
            .setEdition(Instance.Edition.STANDARD)
            .setNodeCount(nodeCount)
            .setConfig(InstanceConfigName.of(projectId, "regional-us-east4").toString())
            .build();

    try (Spanner spanner =
            SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {

      // Wait for the createInstance operation to finish.
      Instance createdInstance =
          instanceAdminClient
              .createInstanceAsync(
                  CreateInstanceRequest.newBuilder()
                      .setParent(ProjectName.of(projectId).toString())
                      .setInstanceId(instanceId)
                      .setInstance(instance)
                      .build())
              .get();
      System.out.printf("Instance %s was successfully created%n", createdInstance.getName());
    } catch (ExecutionException e) {
      System.out.printf(
          "Error: Creating instance %s failed with error message %s%n",
          instance.getName(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
    }
  }
}

使用 Java 建立具有代管自動調度資源功能的執行個體


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.AutoscalingConfig;
import com.google.spanner.admin.instance.v1.CreateInstanceRequest;
import com.google.spanner.admin.instance.v1.Instance;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.ProjectName;
import com.google.spanner.admin.instance.v1.ReplicaSelection;
import java.util.concurrent.ExecutionException;

class CreateInstanceWithAsymmetricAutoscalingConfigExample {

  static void createInstance() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    createInstance(projectId, instanceId);
  }

  static void createInstance(String projectId, String instanceId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      // Set Instance configuration.
      String configId = "nam-eur-asia3";
      String displayName = "Descriptive name";

      // Create an autoscaling config.
      // When autoscaling_config is enabled, node_count and processing_units fields
      // need not be specified.
      // The read-only replicas listed in the asymmetric autoscaling options scale independently
      // from other replicas.
      AutoscalingConfig autoscalingConfig =
          AutoscalingConfig.newBuilder()
              .setAutoscalingLimits(
                  AutoscalingConfig.AutoscalingLimits.newBuilder().setMinNodes(1).setMaxNodes(2))
              .setAutoscalingTargets(
                  AutoscalingConfig.AutoscalingTargets.newBuilder()
                      .setHighPriorityCpuUtilizationPercent(65)
                      .setStorageUtilizationPercent(95))
              .addAsymmetricAutoscalingOptions(
                  AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder()
                  .setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west1")))
              .addAsymmetricAutoscalingOptions(
                  AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder()
                  .setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west4")))
              .addAsymmetricAutoscalingOptions(
                  AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder()
                  .setReplicaSelection(ReplicaSelection.newBuilder().setLocation("asia-east1")))
              .build();
      Instance instance =
          Instance.newBuilder()
              .setAutoscalingConfig(autoscalingConfig)
              .setDisplayName(displayName)
              .setConfig(
                  InstanceConfigName.of(projectId, configId).toString())
              .build();

      // Creates a new instance
      System.out.printf("Creating instance %s.%n", instanceId);
      try {
        // Wait for the createInstance operation to finish.
        Instance instanceResult = instanceAdminClient.createInstanceAsync(
            CreateInstanceRequest.newBuilder()
                .setParent(ProjectName.of(projectId).toString())
                .setInstanceId(instanceId)
                .setInstance(instance)
                .build()).get();
        System.out.printf("Asymmetric Autoscaling instance %s was successfully created%n",
            instanceResult.getName());
      } catch (ExecutionException e) {
        System.out.printf(
            "Error: Creating instance %s failed with error message %s%n",
            instance.getName(), e.getMessage());
      } catch (InterruptedException e) {
        System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
      }
    }
  }
}

使用 Java 建立具備非對稱唯讀自動調整資源配置功能的執行個體


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.AutoscalingConfig;
import com.google.spanner.admin.instance.v1.CreateInstanceRequest;
import com.google.spanner.admin.instance.v1.Instance;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.ProjectName;
import com.google.spanner.admin.instance.v1.ReplicaSelection;
import java.util.concurrent.ExecutionException;

class CreateInstanceWithAsymmetricAutoscalingConfigExample {

  static void createInstance() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    createInstance(projectId, instanceId);
  }

  static void createInstance(String projectId, String instanceId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      // Set Instance configuration.
      String configId = "nam-eur-asia3";
      String displayName = "Descriptive name";

      // Create an autoscaling config.
      // When autoscaling_config is enabled, node_count and processing_units fields
      // need not be specified.
      // The read-only replicas listed in the asymmetric autoscaling options scale independently
      // from other replicas.
      AutoscalingConfig autoscalingConfig =
          AutoscalingConfig.newBuilder()
              .setAutoscalingLimits(
                  AutoscalingConfig.AutoscalingLimits.newBuilder().setMinNodes(1).setMaxNodes(2))
              .setAutoscalingTargets(
                  AutoscalingConfig.AutoscalingTargets.newBuilder()
                      .setHighPriorityCpuUtilizationPercent(65)
                      .setStorageUtilizationPercent(95))
              .addAsymmetricAutoscalingOptions(
                  AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder()
                  .setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west1")))
              .addAsymmetricAutoscalingOptions(
                  AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder()
                  .setReplicaSelection(ReplicaSelection.newBuilder().setLocation("europe-west4")))
              .addAsymmetricAutoscalingOptions(
                  AutoscalingConfig.AsymmetricAutoscalingOption.newBuilder()
                  .setReplicaSelection(ReplicaSelection.newBuilder().setLocation("asia-east1")))
              .build();
      Instance instance =
          Instance.newBuilder()
              .setAutoscalingConfig(autoscalingConfig)
              .setDisplayName(displayName)
              .setConfig(
                  InstanceConfigName.of(projectId, configId).toString())
              .build();

      // Creates a new instance
      System.out.printf("Creating instance %s.%n", instanceId);
      try {
        // Wait for the createInstance operation to finish.
        Instance instanceResult = instanceAdminClient.createInstanceAsync(
            CreateInstanceRequest.newBuilder()
                .setParent(ProjectName.of(projectId).toString())
                .setInstanceId(instanceId)
                .setInstance(instance)
                .build()).get();
        System.out.printf("Asymmetric Autoscaling instance %s was successfully created%n",
            instanceResult.getName());
      } catch (ExecutionException e) {
        System.out.printf(
            "Error: Creating instance %s failed with error message %s%n",
            instance.getName(), e.getMessage());
      } catch (InterruptedException e) {
        System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
      }
    }
  }
}

建立不含預設備份排程的執行個體


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.CreateInstanceRequest;
import com.google.spanner.admin.instance.v1.Instance;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.ProjectName;
import java.util.concurrent.ExecutionException;

class CreateInstanceWithoutDefaultBackupSchedulesExample {

  static void createInstanceWithoutDefaultBackupSchedules() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    createInstanceWithoutDefaultBackupSchedules(projectId, instanceId);
  }

  static void createInstanceWithoutDefaultBackupSchedules(String projectId, String instanceId) {
    // Set Instance configuration.
    int nodeCount = 2;
    String displayName = "Descriptive name";

    // Create an Instance object that will be used to create the instance.
    Instance instance =
        Instance.newBuilder()
            .setDisplayName(displayName)
            .setDefaultBackupScheduleType(Instance.DefaultBackupScheduleType.NONE)
            .setNodeCount(nodeCount)
            .setConfig(InstanceConfigName.of(projectId, "regional-us-east4").toString())
            .build();

    try (Spanner spanner =
            SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {

      // Wait for the createInstance operation to finish.
      Instance createdInstance =
          instanceAdminClient
              .createInstanceAsync(
                  CreateInstanceRequest.newBuilder()
                      .setParent(ProjectName.of(projectId).toString())
                      .setInstanceId(instanceId)
                      .setInstance(instance)
                      .build())
              .get();
      System.out.printf("Instance %s was successfully created%n", createdInstance.getName());
    } catch (ExecutionException e) {
      System.out.printf(
          "Error: Creating instance %s failed with error message %s%n",
          instance.getName(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


// Imports the Google Cloud client library
const {Spanner, protos} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = await spanner.getInstanceAdminClient();
/**
 * TODO(developer): Uncomment the following lines before running the sample.
 **/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';

// Creates a new instance
try {
  console.log(
    `Creating instance ${instanceAdminClient.instancePath(
      projectId,
      instanceId,
    )}.`,
  );
  const [operation] = await instanceAdminClient.createInstance({
    instanceId: instanceId,
    parent: instanceAdminClient.projectPath(projectId),
    instance: {
      config: instanceAdminClient.instanceConfigPath(
        projectId,
        'regional-us-central1',
      ),
      nodeCount: 1,
      displayName: 'Display name for the instance.',
      labels: {
        cloud_spanner_samples: 'true',
        created: Math.round(Date.now() / 1000).toString(), // current time
      },
      edition:
        protos.google.spanner.admin.instance.v1.Instance.Edition.STANDARD, //optional
    },
  });

  console.log(`Waiting for operation on ${instanceId} to complete...`);
  await operation.promise();

  console.log(`Created instance ${instanceId}.`);
} catch (err) {
  console.error('ERROR:', err);
}

使用 Node.js 建立具有代管自動調度資源功能的執行個體

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Imports the Google Cloud client library
const {Spanner, protos} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

// Get the instance admin client
const instanceAdminClient = spanner.getInstanceAdminClient();

const autoscalingConfig =
  protos.google.spanner.admin.instance.v1.AutoscalingConfig.create({
    // Only one of minNodes/maxNodes or minProcessingUnits/maxProcessingUnits can be set.
    autoscalingLimits:
      protos.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.create(
        {
          minNodes: 1,
          maxNodes: 2,
        },
      ),
    // highPriorityCpuUtilizationPercent and storageUtilizationPercent are both
    // percentages and must lie between 0 and 100.
    autoscalingTargets:
      protos.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.create(
        {
          highPriorityCpuUtilizationPercent: 65,
          storageUtilizationPercent: 95,
        },
      ),
  });

// Creates a new instance with autoscaling configuration
// When autoscalingConfig is enabled, nodeCount and processingUnits fields
// need not be specified.
try {
  console.log(
    `Creating instance ${instanceAdminClient.instancePath(
      projectId,
      instanceId,
    )}.`,
  );
  const [operation] = await instanceAdminClient.createInstance({
    instanceId: instanceId,
    parent: instanceAdminClient.projectPath(projectId),
    instance: {
      config: instanceAdminClient.instanceConfigPath(
        projectId,
        'regional-us-central1',
      ),
      displayName: 'Display name for the instance.',
      autoscalingConfig: autoscalingConfig,
      labels: {
        cloud_spanner_samples: 'true',
        created: Math.round(Date.now() / 1000).toString(), // current time
      },
      // Managed autoscaler is available only for ENTERPRISE edition
      edition:
        protos.google.spanner.admin.instance.v1.Instance.Edition.ENTERPRISE,
    },
  });

  console.log(`Waiting for operation on ${instanceId} to complete...`);
  await operation.promise();
  console.log(`Created instance ${instanceId}.`);

  // get instance metadata
  const [metadata] = await instanceAdminClient.getInstance({
    name: instanceAdminClient.instancePath(projectId, instanceId),
  });
  console.log(
    `Autoscaling configurations of ${instanceId} are:  ` +
      '\n' +
      `Min nodes: ${metadata.autoscalingConfig.autoscalingLimits.minNodes} ` +
      'nodes.' +
      '\n' +
      `Max nodes: ${metadata.autoscalingConfig.autoscalingLimits.maxNodes}` +
      ' nodes.' +
      '\n' +
      `High priority cpu utilization percent: ${metadata.autoscalingConfig.autoscalingTargets.highPriorityCpuUtilizationPercent}.` +
      '\n' +
      `Storage utilization percent: ${metadata.autoscalingConfig.autoscalingTargets.storageUtilizationPercent}.`,
  );
} catch (err) {
  console.error('ERROR:', err);
}

建立不含預設備份排程的執行個體

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 **/
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';

// Imports the Google Cloud client library
const {Spanner, protos} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = await spanner.getInstanceAdminClient();
// Creates a new instance
try {
  const [operation] = await instanceAdminClient.createInstance({
    instanceId: instanceId,
    parent: instanceAdminClient.projectPath(projectId),
    instance: {
      config: instanceAdminClient.instanceConfigPath(
        projectId,
        'regional-me-central2',
      ),
      nodeCount: 1,
      displayName: 'Display name for the instance.',
      labels: {
        cloud_spanner_samples: 'true',
        created: Math.round(Date.now() / 1000).toString(), // current time
      },
      defaultBackupScheduleType:
        protos.google.spanner.admin.instance.v1.Instance
          .DefaultBackupScheduleType.NONE,
    },
  });
  await operation.promise();

  console.log(
    `Created instance ${instanceId} without default backup schedules.`,
  );
} catch (err) {
  console.error('ERROR:', err);
}

PHP

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\CreateInstanceRequest;
use Google\Cloud\Spanner\Admin\Instance\V1\Instance;

/**
 * Creates an instance.
 * Example:
 * ```
 * create_instance($projectId, $instanceId);
 * ```
 *
 * @param string $projectId  The Spanner project ID.
 * @param string $instanceId The Spanner instance ID.
 */
function create_instance(string $projectId, string $instanceId): void
{
    $instanceAdminClient = new InstanceAdminClient();
    $parent = InstanceAdminClient::projectName($projectId);
    $instanceName = InstanceAdminClient::instanceName($projectId, $instanceId);
    $configName = $instanceAdminClient->instanceConfigName($projectId, 'regional-us-central1');
    $instance = (new Instance())
        ->setName($instanceName)
        ->setConfig($configName)
        ->setDisplayName('dispName')
        ->setNodeCount(1);

    $operation = $instanceAdminClient->createInstance(
        (new CreateInstanceRequest())
        ->setParent($parent)
        ->setInstanceId($instanceId)
        ->setInstance($instance)
    );

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Created instance %s' . PHP_EOL, $instanceId);
}

Python

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

def create_instance(instance_id):
    """Creates an instance."""
    from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin

    spanner_client = spanner.Client()

    config_name = "{}/instanceConfigs/regional-us-central1".format(
        spanner_client.project_name
    )

    operation = spanner_client.instance_admin_api.create_instance(
        parent=spanner_client.project_name,
        instance_id=instance_id,
        instance=spanner_instance_admin.Instance(
            config=config_name,
            display_name="This is a display name.",
            node_count=1,
            labels={
                "cloud_spanner_samples": "true",
                "sample_name": "snippets-create_instance-explicit",
                "created": str(int(time.time())),
            },
            edition=spanner_instance_admin.Instance.Edition.STANDARD,  # Optional
        ),
    )

    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)

    print("Created instance {}".format(instance_id))

使用 Python 建立具有代管自動調度資源功能的執行個體

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

def create_instance_with_autoscaling_config(instance_id):
    """Creates a Cloud Spanner instance with an autoscaling configuration."""
    from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin

    spanner_client = spanner.Client()

    config_name = "{}/instanceConfigs/regional-us-central1".format(
        spanner_client.project_name
    )

    autoscaling_config = spanner_instance_admin.AutoscalingConfig(
        # Only one of minNodes/maxNodes or minProcessingUnits/maxProcessingUnits can be set.
        autoscaling_limits=spanner_instance_admin.AutoscalingConfig.AutoscalingLimits(
            min_nodes=1,
            max_nodes=2,
        ),
        # highPriorityCpuUtilizationPercent and storageUtilizationPercent are both
        # percentages and must lie between 0 and 100.
        autoscaling_targets=spanner_instance_admin.AutoscalingConfig.AutoscalingTargets(
            high_priority_cpu_utilization_percent=65,
            storage_utilization_percent=95,
        ),
    )

    #  Creates a new instance with autoscaling configuration
    #  When autoscalingConfig is enabled, nodeCount and processingUnits fields
    #  need not be specified.
    request = spanner_instance_admin.CreateInstanceRequest(
        parent=spanner_client.project_name,
        instance_id=instance_id,
        instance=spanner_instance_admin.Instance(
            config=config_name,
            display_name="This is a display name.",
            autoscaling_config=autoscaling_config,
            labels={
                "cloud_spanner_samples": "true",
                "sample_name": "snippets-create_instance_with_autoscaling_config",
                "created": str(int(time.time())),
            },
            edition=spanner_instance_admin.Instance.Edition.ENTERPRISE,  # Optional
        ),
    )

    operation = spanner_client.instance_admin_api.create_instance(request=request)

    print("Waiting for operation to complete...")
    instance = operation.result(OPERATION_TIMEOUT_SECONDS)

    print(
        "Created instance {} with {} autoscaling config".format(
            instance_id, instance.autoscaling_config
        )
    )

建立不含預設備份排程的執行個體

def create_instance_without_default_backup_schedules(instance_id):
    spanner_client = spanner.Client()
    config_name = "{}/instanceConfigs/regional-me-central2".format(
        spanner_client.project_name
    )

    operation = spanner_client.instance_admin_api.create_instance(
        parent=spanner_client.project_name,
        instance_id=instance_id,
        instance=spanner_instance_admin.Instance(
            config=config_name,
            display_name="This is a display name.",
            node_count=1,
            default_backup_schedule_type=spanner_instance_admin.Instance.DefaultBackupScheduleType.NONE,  # Optional
        ),
    )

    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)

    print("Created instance {} without default backup schedules".format(instance_id))

小茹

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

# project_id  = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# instance_config_id = "Your Spanner InstanceConfig ID"

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin

project_path = instance_admin_client.project_path project: project_id
instance_path = instance_admin_client.instance_path project: project_id, instance: instance_id
instance_config_path = instance_admin_client.instance_config_path project: project_id, instance_config: instance_config_id

job = instance_admin_client.create_instance parent: project_path,
                                            instance_id: instance_id,
                                            instance: { name: instance_path,
                                                        config: instance_config_path,
                                                        display_name: instance_id,
                                                        node_count: 2,
                                                        labels: { cloud_spanner_samples: "true" } }

puts "Waiting for create instance operation to complete"

job.wait_until_done!

if job.error?
  puts job.error
else
  puts "Created instance #{instance_id}"
end

列出執行個體

您可以顯示 Spanner 執行個體清單。

控制台

前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

前往「Instances」(執行個體) 頁面

Google Cloud 控制台會顯示 Spanner 執行個體清單,以及各執行個體的 ID、顯示名稱、設定和運算能力 (以處理單元和節點表示)。

gcloud

使用 gcloud spanner instances list 指令:

gcloud spanner instances list

gcloud CLI 會列印 Spanner 執行個體清單,以及各個執行個體的 ID、顯示名稱、設定和運算能力。

編輯執行個體

下列各節說明如何升級執行個體版本,以及變更執行個體的顯示名稱、運算能力和預設備份排程類型。您無法變更執行個體 ID 或執行個體設定 (但可以移動執行個體)。

升級版本

您可以將 Standard 版本執行個體升級至更高階的版本。只要未受組織政策限制阻礙,Standard 版執行個體即可升級至 Enterprise 版或 Enterprise Plus 版。Enterprise 版執行個體可以升級至 Enterprise Plus 版。版本升級作業約需 10 分鐘才能完成,期間不會停機。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 按一下要升級的執行個體名稱。

  3. 按一下版本類型旁的「升級」。

  4. 在「Edition instance」(版本執行個體) 頁面的「Update edition」(更新版本) 下方,為執行個體選取新的高階版本。

  5. 按一下 [儲存]。

gcloud

使用 gcloud spanner instances update 指令升級執行個體版本:

gcloud spanner instances update INSTANCE_ID --edition=EDITION \
[--async]

更改下列內容:

  • INSTANCE_ID:執行個體的永久 ID。
  • EDITION:為執行個體指定新的高階版本。詳情請參閱「Spanner 版本總覽」。

選用標記:

  • --async:如要立即傳回要求,不必等待進行中的作業完成,請使用這個旗標。您可以執行 gcloud spanner operations describe,查看要求的狀態。

Go

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/genproto/protobuf/field_mask"
)

func updateInstance(w io.Writer, projectID, instanceID string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance"
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	req := &instancepb.UpdateInstanceRequest{
		Instance: &instancepb.Instance{
			Name: fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID),
			// The edition selected for this instance.
			// Different editions provide different capabilities at different price points.
			// For more information, see https://cloud.google.com/spanner/docs/editions-overview.
			Edition: instancepb.Instance_ENTERPRISE,
		},
		FieldMask: &field_mask.FieldMask{
			Paths: []string{"edition"},
		},
	}
	op, err := instanceAdmin.UpdateInstance(ctx, req)
	if err != nil {
		return fmt.Errorf("could not update instance %s: %w", fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID), err)
	}
	// Wait for the instance update to finish.
	_, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance update to finish failed: %w", err)
	}

	fmt.Fprintf(w, "Updated instance [%s]\n", instanceID)
	return nil
}

Java


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.common.collect.Lists;
import com.google.protobuf.FieldMask;
import com.google.spanner.admin.instance.v1.Instance;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.InstanceName;
import com.google.spanner.admin.instance.v1.UpdateInstanceRequest;
import java.util.concurrent.ExecutionException;

public class UpdateInstanceExample {

  static void updateInstance() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    updateInstance(projectId, instanceId);
  }

  static void updateInstance(String projectId, String instanceId) {
    // Set Instance configuration.
    int nodeCount = 2;
    String displayName = "Updated name";

    // Update an Instance object that will be used to update the instance.
    Instance instance =
        Instance.newBuilder()
            .setName(InstanceName.of(projectId, instanceId).toString())
            .setDisplayName(displayName)
            .setNodeCount(nodeCount)
            .setEdition(Instance.Edition.ENTERPRISE)
            .setConfig(InstanceConfigName.of(projectId, "regional-us-east4").toString())
            .build();

    try (Spanner spanner =
            SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {

      // Wait for the updatedInstance operation to finish.
      Instance updatedInstance =
          instanceAdminClient
              .updateInstanceAsync(
                  UpdateInstanceRequest.newBuilder()
                      .setFieldMask(
                          FieldMask.newBuilder().addAllPaths(Lists.newArrayList("edition")))
                      .setInstance(instance)
                      .build())
              .get();
      System.out.printf("Instance %s was successfully updated%n", updatedInstance.getName());
    } catch (ExecutionException e) {
      System.out.printf(
          "Error: Updating instance %s failed with error message %s%n",
          instance.getName(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: Waiting for updateInstance operation to finish was interrupted");
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


// Imports the Google Cloud client library
const {Spanner, protos} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

// Updates an instance
try {
  console.log(
    `Updating instance ${instanceAdminClient.instancePath(
      projectId,
      instanceId,
    )}.`,
  );
  const [operation] = await instanceAdminClient.updateInstance({
    instance: {
      name: instanceAdminClient.instancePath(projectId, instanceId),
      labels: {
        updated: 'true',
        created: Math.round(Date.now() / 1000).toString(), // current time
      },
      edition:
        protos.google.spanner.admin.instance.v1.Instance.Edition.ENTERPRISE, //optional
    },
    // Field mask specifying fields that should get updated in an Instance
    fieldMask: (protos.google.protobuf.FieldMask = {
      paths: ['labels', 'edition'],
    }),
  });

  console.log(`Waiting for operation on ${instanceId} to complete...`);
  await operation.promise();
  console.log(`Updated instance ${instanceId}.`);
  const [metadata] = await instanceAdminClient.getInstance({
    name: instanceAdminClient.instancePath(projectId, instanceId),
  });
  console.log(
    `Instance ${instanceId} has been updated with the ${metadata.edition} ` +
      'edition.',
  );
} catch (err) {
  console.error('ERROR:', err);
}

Python

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

def update_instance(instance_id):
    """Updates an instance."""
    from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin

    spanner_client = spanner.Client()

    name = "{}/instances/{}".format(spanner_client.project_name, instance_id)

    operation = spanner_client.instance_admin_api.update_instance(
        instance=spanner_instance_admin.Instance(
            name=name,
            labels={
                "sample_name": "snippets-update_instance-explicit",
            },
            edition=spanner_instance_admin.Instance.Edition.ENTERPRISE,  # Optional
        ),
        field_mask=field_mask_pb2.FieldMask(paths=["labels", "edition"]),
    )

    print("Waiting for operation to complete...")
    operation.result(900)

    print("Updated instance {}".format(instance_id))

降級版本

您可以將 Spanner 執行個體降級為較低級別的版本。您必須停止使用較高版本的專屬功能,才能降級。Enterprise 版執行個體可以降級為 Standard 版。Enterprise Plus 版執行個體可以降級為 Enterprise 版或 Standard 版。降級作業約需 10 分鐘才能完成,期間不會停機。

如要監控執行個體中 Enterprise 版和 Enterprise Plus 版功能的使用情形,請使用功能用量 (instance/edition/feature_usage) 監控指標。詳情請參閱「監控版本用量」

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 按一下要降級的執行個體名稱。

  3. 在「執行個體總覽」頁面,點選「編輯執行個體」。

  4. 在「Edit instance」(編輯執行個體) 頁面的「Choose a Spanner edition」(選擇 Spanner 版本) 下方,選取較低階的版本。

  5. 按一下「更新執行個體」。

gcloud

使用 gcloud spanner instances update 指令,將執行個體降級:

gcloud spanner instances update INSTANCE_ID --edition=EDITION

更改下列內容:

  • INSTANCE_ID:執行個體的永久 ID。
  • EDITION:為執行個體指定新的低階版本。詳情請參閱「Spanner 版本總覽」。

變更顯示名稱

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 按一下您要重新命名的執行個體名稱。

  3. 按一下 [Edit instance] (編輯執行個體)。

  4. 輸入新執行個體的名稱。這個名稱在Google Cloud 專案中不得重複。

  5. 按一下 [儲存]。

gcloud

使用 gcloud spanner instances update 指令:

gcloud spanner instances update INSTANCE_ID --description=INSTANCE_NAME

更改下列內容:

  • INSTANCE_ID:執行個體的永久 ID。
  • INSTANCE_NAME:執行個體在Google Cloud 控制台中的顯示名稱。執行個體名稱在Google Cloud 專案中不得重複。

變更運算能力

您必須佈建足夠的運算資源,將 CPU 使用率和儲存空間使用率維持在建議最大值以下。詳情請參閱 Spanner 的配額與限制。

您可以降低 Spanner 執行個體的運算能力,但下列情況除外:

  • 每個節點 (1,000 個處理單元) 最多只能儲存 10 TiB 的資料。

  • 執行個體資料有大量分割。在這種情況下,Spanner 可能無法在您減少運算能力後管理分割。您可以嘗試逐步減少運算資源,直到找出 Spanner 管理執行個體所有分割所需的最低資源。

    Spanner 可建立大量分割,以配合您的使用模式。如果使用模式有所變更,Spanner 可能會在一到兩週後合併部分分割,屆時您可以嘗試降低執行個體的運算能力。

移除運算能力時,請在 Cloud Monitoring 中監控 CPU 使用率和要求延遲時間,確保區域執行個體的 CPU 使用率維持在 65% 以下,多區域執行個體中各區域的 CPU 使用率則維持在 45% 以下。移除運算資源時,要求延遲時間可能會暫時增加。

如要提高執行個體的運算能力,Google Cloud 專案必須有足夠的配額,才能增加運算能力。完成增加要求所需的時間取決於要求的大小。在多數情況下,要求會在幾分鐘內完成。在極少數情況下,擴充作業最多可能需要一小時才能完成。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 按一下要變更的執行個體名稱。

  3. 按一下 [Edit Instance] (編輯執行個體)。

  4. 如要變更運算能力,請選擇測量單位 (處理單元或節點),然後輸入數量。使用處理單元時,請以 100 的倍數 (100、200、300 等) 輸入最多 1000 的數量,並以 1000 的倍數 (1000、2000、3000 等) 輸入更大的數量。每個節點等於 1,000 個處理單元。

  5. 按一下 [儲存]。

如果對話方塊顯示配額不足,無法在這個位置新增運算能力,請按照操作說明申請提高配額。

gcloud

使用 gcloud spanner instances update 指令。使用這個指令時,請將運算資源指定為節點或處理單元的數量。

gcloud spanner instances update INSTANCE_ID --nodes=NODE_COUNT
[--async]

或

gcloud spanner instances update INSTANCE_ID
--processing-units=PROCESSING_UNIT_COUNT [--async]

更改下列內容:

  • INSTANCE_ID:執行個體的永久 ID。
  • NODE_COUNT:執行個體的運算能力,以節點數量表示。每個節點等於 1,000 個處理單元。
  • PROCESSING_UNIT_COUNT:執行個體的運算資源,以處理單元數量表示。1,000 以下請輸入 100 的倍數 (100、200、300 等),超過 1,000 則請輸入 1,000 的倍數 (1,000、2,000、3,000 等)。

選用標記:

  • --async:如要立即傳回要求,不必等待進行中的作業完成,請使用這個旗標。您可以執行 gcloud spanner operations describe,查看要求的狀態。

啟用或修改執行個體的代管自動配置器

您可以使用 Google Cloud 控制台、gcloud CLI 或 Spanner 用戶端程式庫,啟用或修改 Spanner 執行個體的自動調度資源功能。在現有執行個體中新增或變更代管自動調度資源功能時,須遵守下列限制:

  • 代管自動配置器僅適用於 Enterprise 或 Enterprise Plus 版本。
  • 您無法在移動中的執行個體上啟用代管自動配置器。
  • 啟用代管自動配置器時,您無法移動執行個體。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 按一下要啟用代管自動配置器的執行個體名稱。

  3. 按一下 [Edit instance] (編輯執行個體)。

  4. 在「設定運算能力」下方,按一下「自動調度資源」。

  5. 在「Minimum」(下限) 部分,選取縮減時要使用的下限。詳情請參閱「判斷最低限制」。

  6. 在「Maximum」(上限) 部分,選取向上擴充時要使用的上限。詳情請參閱「判斷上限」一節。

  7. 在「High priority CPU utilization target」(高優先順序 CPU 使用率目標),選取要用於高優先順序工作的 CPU 百分比。詳情請參閱「決定 CPU 使用率目標」。

  8. 在「Total CPU utilization target」(CPU 總使用率目標) 部分,選取要用於所有低、中、高優先順序工作的目標 CPU 百分比。CPU 百分比可以介於 10% 到 90% 之間。詳情請參閱「決定 CPU 總使用率目標」。

  9. 在「Storage utilization target」(儲存空間使用率目標) 中,選取要使用的儲存空間百分比。詳情請參閱「決定儲存空間使用率目標」。

  10. 選用:如果選取「自動調度資源」做為調度模式,可以點選「顯示非對稱自動調度資源選項」下拉式選單,自動調度唯讀副本的資源,不受其他副本影響。

    1. 選取要非對稱自動調度資源的唯讀副本。

    2. 設定下列自動配置器選項:

      • 「Minimum」(最小值) 表示縮減資源的下限,具體取決於您為「Compute capacity」(運算能力) 選擇的測量單位。詳情請參閱「判斷最低限制」。
      • 「Maximum」(最大值) 表示可擴充的最大限制,具體取決於您為「Compute capacity」(運算能力) 選擇的測量單位。詳情請參閱「判斷上限」。
      • 「高優先順序 CPU 使用率目標」是指高優先順序工作要使用的 CPU 目標百分比。詳情請參閱「決定高優先順序 CPU 使用率目標」。
      • 「Total CPU utilization target」(CPU 總使用率目標) 表示所有低、中、高優先順序工作的 CPU 使用率目標百分比。CPU 百分比可以介於 10% 到 90% 之間。詳情請參閱「決定 CPU 總使用率目標」。
  11. 按一下 [儲存]。

gcloud

使用 gcloud spanner instances update 指令,將代管自動配置器新增至執行個體。如要進一步瞭解相關資訊和限制,請參閱「Google Cloud CLI 旗標和限制」。

您可以使用下列指令新增代管自動配置器:

  gcloud spanner instances update INSTANCE_ID \
    --autoscaling-min-processing-units=MINIMUM_PROCESSING_UNITS \
    --autoscaling-max-processing-units=MAXIMUM_PROCESSING_UNITS \
    --autoscaling-high-priority-cpu-target=HIGH_PRIORITY_CPU_PERCENTAGE \
    --autoscaling-total-cpu-target=TOTAL_CPU_PERCENTAGE \
    --autoscaling-storage-target=STORAGE_PERCENTAGE \
    [--disable-downscaling | --no-disable-downscaling] \
    [--asymmetric-autoscaling-option \
       location=ASYMMETRIC_AUTOSCALING_LOCATION,\
       min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\
       max_nodes=ASYMMETRIC_AUTOSCALING_MAX,\
       high_priority_cpu_target=ASYMMETRIC_HIGH_PRIORITY_CPU_TARGET,\
       total_cpu_target=ASYMMETRIC_TOTAL_CPU_TARGET,\
       disable_total_cpu_autoscaling=TRUE|FALSE
       | disable_high_priority_cpu_autoscaling=TRUE|FALSE]

或

  gcloud spanner instances update INSTANCE_ID \
    --autoscaling-min-processing-units=MINIMUM_NODES \
    --autoscaling-max-processing-units=MAXIMUM_NODES \
    --autoscaling-high-priority-cpu-target=HIGH_PRIORITY_CPU_PERCENTAGE \
    --autoscaling-total-cpu-target=TOTAL_CPU_PERCENTAGE \
    --autoscaling-storage-target=STORAGE_PERCENTAGE \
    [--disable-downscaling | --no-disable-downscaling] \
    [--asymmetric-autoscaling-option \
       location=ASYMMETRIC_AUTOSCALING_LOCATION,\
       min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\
       max_nodes=ASYMMETRIC_AUTOSCALING_MAX,\
       high_priority_cpu_target=ASYMMETRIC_HIGH_PRIORITY_CPU_TARGET,\
       total_cpu_target=ASYMMETRIC_TOTAL_CPU_TARGET,\
       disable_total_cpu_autoscaling=TRUE|FALSE
       | disable_high_priority_cpu_autoscaling=TRUE|FALSE]

更改下列內容:

  • INSTANCE_ID:執行個體的永久 ID。
  • MINIMUM_PROCESSING_UNITS、MINIMUM_NODES:縮減時要使用的處理單元或節點數量下限。詳情請參閱「判斷最低限制」。
  • MAXIMUM_PROCESSING_UNITS、MAXIMUM_NODES:向上擴充時使用的處理單元或節點數量上限。詳情請參閱「判斷上限」一節。
  • HIGH_PRIORITY_CPU_PERCENTAGE:根據工作優先順序,設定高優先順序 CPU 的目標使用率。CPU 百分比可以介於 10% 到 90% 之間。如要盡可能降低成本,請使用較高的百分比。詳情請參閱「決定高優先順序 CPU 使用率目標」。
  • TOTAL_CPU_PERCENTAGE:要使用的優先 CPU 總量目標百分比。總 CPU 目標必須大於高優先順序 CPU 目標。CPU 百分比可以介於 10% 到 90% 之間。如要盡可能降低費用,請使用較高的百分比。詳情請參閱「決定 CPU 總使用率目標」。
  • STORAGE_PERCENTAGE:要使用的儲存空間目標百分比,範圍為 10% 到 99%。詳情請參閱「決定儲存空間使用率目標」。

選用標記:

  • --disable-downscaling:使用這個布林值旗標停用縮減功能。如果設為 TRUE,自動配置器就不會減少節點或處理單元數量。系統會繼續正常擴充,以因應增加的需求。如要在停用後啟用縮減功能,請使用 --no-disable-downscaling 旗標。
  • --asymmetric-autoscaling-option:使用這個旗標啟用非對稱自動調度資源。

    替換下列參數:

    • ASYMMETRIC_AUTOSCALING_LOCATION:如果使用非對稱自動調度資源旗標,則必須提供這項參數。要以非對稱方式調度資源的唯讀區域位置。
    • ASYMMETRIC_AUTOSCALING_MIN:選用參數。縮減時的節點數量下限。如未指定,這個值會沿用基礎執行個體設定。
    • ASYMMETRIC_AUTOSCALING_MAX:選用參數。向上擴充時的節點數量上限。如未指定,這個值會沿用基礎執行個體設定。
    • ASYMMETRIC_HIGH_PRIORITY_CPU_TARGET:選用參數。根據工作優先順序,設定要使用的 CPU 目標百分比。如未指定,這個值會沿用基礎執行個體設定。如果想盡可能降低成本,請使用較高的百分比。副本的目標百分比可以與基本執行個體和其他副本不同,但如果是容錯移轉情境,建議副本在不同副本之間使用一致的目標。詳情請參閱「容錯移轉相關問題」。
    • ASYMMETRIC_TOTAL_CPU_TARGET:選用參數。將總 CPU 的目標設為 10% 到 90%。如未指定,這個值會沿用基礎執行個體設定。如果想盡可能降低成本,請使用較高的百分比。副本的目標百分比可以與基本執行個體和其他副本不同,但如果是容錯移轉情境,建議副本在不同副本之間使用一致的目標。詳情請參閱「非對稱自動調度唯讀資源」。
    • disable_total_cpu_autoscaling:如果您不希望自動配置器自動調度副本的總 CPU 資源,請將這個參數設為 TRUE。如要讓執行個體從基本執行個體繼承 total_cpu_autoscaling 目標,請勿指定這個參數。您無法在同一個副本上同時停用 CPU 總用量和高優先順序 CPU。
    • disable_high_priority_cpu_autoscaling:如果不希望自動配置器自動調度副本的高優先順序 CPU 資源,請將 disable_high_priority_cpu_autoscaling 設為 TRUE。如要讓執行個體從基本執行個體繼承 high_priority_cpu_autoscaling 目標,請勿指定這個參數。您無法在同一個副本上同時停用總 CPU 和高優先順序 CPU。

將代管自動配置器新增至執行個體後,您也可以修改代管自動配置器設定。舉例來說,如要將處理單元數量上限提高至 10000,請執行下列指令:

gcloud spanner instances update test-instance \
     --autoscaling-max-processing-units=10000

將執行個體從使用代管自動配置器變更為手動調度資源

您可以使用 Google Cloud 控制台、gcloud CLI 或 Spanner 用戶端程式庫,變更 Spanner 執行個體要使用手動或代管級資源調度功能。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 按一下要停用代管自動配置器的執行個體名稱。

  3. 在「Choose a scaling mode」(選擇資源調度模式) 下方,按一下「Manual allocation」(手動分配)。

  4. 按一下 [儲存]。

gcloud

使用 gcloud spanner instances update 指令更新執行個體。

使用下列指令,將執行個體從使用代管自動配置器變更為手動調度資源:

  gcloud spanner instances update INSTANCE_ID \
  --processing-units=PROCESSING_UNIT_COUNT

或

  gcloud spanner instances update INSTANCE_ID \
  --nodes=NODE_COUNT

更改下列內容:

  • INSTANCE_ID:執行個體的永久 ID。
  • NODE_COUNT:執行個體的運算能力,以節點數量表示。每個節點等於 1,000 個處理單元。
  • PROCESSING_UNIT_COUNT:執行個體的運算資源,以處理單元數量表示。1,000 以下請輸入 100 的倍數 (100、200、300 等),超過 1,000 則請輸入 1,000 的倍數 (1,000、2,000、3,000 等)。

為執行個體加上標籤

標籤可協助您管理資源。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 勾選執行個體的核取方塊。資訊面板會顯示在頁面右側。

  3. 按一下「資訊面板」中的「標籤」分頁標籤。接著,您可以新增、刪除或更新 Spanner 執行個體的標籤。

編輯預設的備份排程類型

所有新執行個體都會自動啟用預設備份排程。您可以在建立執行個體時,或在日後編輯執行個體時,啟用或停用執行個體的預設備份排程。詳情請參閱「預設備份排程」。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

前往「Instances」(執行個體) 頁面

  1. 按一下要編輯預設備份排程的執行個體名稱。
  2. 按一下 [Edit instance] (編輯執行個體)。
  3. 在「Backups」(備份) 下方,勾選「Enable default backup schedules」(啟用預設備份排程) 核取方塊,即可啟用預設備份排程。啟用後,這個執行個體中的所有新資料庫都會建立預設備份排程。
  4. 按一下 [儲存]。

gcloud

使用 gcloud spanner instances update 指令,編輯預設備份排程類型。

執行下列指令,即可編輯預設備份排程類型:

  gcloud spanner instances update INSTANCE_ID \
    --default-backup-schedule-type=DEFAULT_BACKUP_SCHEDULE_TYPE

更改下列內容:

  • INSTANCE_ID:執行個體的永久 ID。
  • DEFAULT_BACKUP_SCHEDULE_TYPE:執行個體使用的預設備份排程類型。必須是下列其中一個值:

    • AUTOMATIC:在執行個體中建立新資料庫時,系統會自動建立預設備份排程。預設備份排程每 24 小時會建立完整備份。這些完整備份會保留 7 天。建立預設備份排程後,您可以編輯或刪除。
    • NONE:在執行個體中建立新的資料庫時,系統不會自動建立預設備份排程。

C#

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Threading.Tasks;

public class UpdateInstanceDefaultBackupScheduleTypeAsyncSample
{
    public async Task<Instance> UpdateInstanceDefaultBackupScheduleTypeAsync(string projectId, string instanceId)
    {
        // Create the InstanceAdminClient instance.
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();

        // Initialize request parameters.
        Instance instance = new Instance
        {
            InstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            DefaultBackupScheduleType = Instance.Types.DefaultBackupScheduleType.Automatic,
        };
        FieldMask mask = new FieldMask 
        {
            Paths = { "default_backup_schedule_type" }
        };

        // Make the CreateInstance request.
        Operation<Instance, UpdateInstanceMetadata> response =
            await instanceAdminClient.UpdateInstanceAsync(instance, mask);

        Console.WriteLine("Waiting for the operation to finish.");

        // Poll until the returned long-running operation is complete.
        Operation<Instance, UpdateInstanceMetadata> completedResponse =
            await response.PollUntilCompletedAsync();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Error while updating instance: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        Console.WriteLine($"Instance updated successfully.");
        return completedResponse.Result;
    }
}

Go

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// updateInstanceDefaultBackupScheduleType updates instance default backup schedule type to AUTOMATIC.
// This means a default backup schedule will be created automatically on creation of a database within the instance.
func updateInstanceDefaultBackupScheduleType(w io.Writer, projectID, instanceID string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance"
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	// Updates the default backup schedule type field of an instance.  The field mask is required to
	// indicate which field is being updated.
	req := &instancepb.UpdateInstanceRequest{
		Instance: &instancepb.Instance{
			Name: fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID),
			// Controls the default backup behavior for new databases within the instance.
			DefaultBackupScheduleType: instancepb.Instance_AUTOMATIC,
		},
		FieldMask: &field_mask.FieldMask{
			Paths: []string{"default_backup_schedule_type"},
		},
	}
	op, err := instanceAdmin.UpdateInstance(ctx, req)
	if err != nil {
		return fmt.Errorf("could not update instance %s: %w", fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID), err)
	}
	// Wait for the instance update to finish.
	_, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance update to finish failed: %w", err)
	}

	fmt.Fprintf(w, "Updated instance [%s]\n", instanceID)
	return nil
}

Java

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.common.collect.Lists;
import com.google.protobuf.FieldMask;
import com.google.spanner.admin.instance.v1.Instance;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.InstanceName;
import com.google.spanner.admin.instance.v1.UpdateInstanceRequest;
import java.util.concurrent.ExecutionException;

public class UpdateInstanceDefaultBackupScheduleTypeExample {

  static void updateInstanceDefaultBackupScheduleType() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    updateInstanceDefaultBackupScheduleType(projectId, instanceId);
  }

  static void updateInstanceDefaultBackupScheduleType(String projectId, String instanceId) {
    // Set Instance configuration.
    int nodeCount = 2;
    String displayName = "Updated name";

    // Update an Instance object that will be used to update the instance.
    Instance instance =
        Instance.newBuilder()
            .setName(InstanceName.of(projectId, instanceId).toString())
            .setDisplayName(displayName)
            .setNodeCount(nodeCount)
            .setDefaultBackupScheduleType(Instance.DefaultBackupScheduleType.AUTOMATIC)
            .setConfig(InstanceConfigName.of(projectId, "regional-us-east4").toString())
            .build();

    try (Spanner spanner =
            SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {

      // Wait for the updatedInstance operation to finish.
      Instance updatedInstance =
          instanceAdminClient
              .updateInstanceAsync(
                  UpdateInstanceRequest.newBuilder()
                      .setFieldMask(
                          FieldMask.newBuilder()
                              .addAllPaths(Lists.newArrayList("default_backup_schedule_type")))
                      .setInstance(instance)
                      .build())
              .get();
      System.out.printf("Instance %s was successfully updated%n", updatedInstance.getName());
    } catch (ExecutionException e) {
      System.out.printf(
          "Error: Updating instance %s failed with error message %s%n",
          instance.getName(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: Waiting for updateInstance operation to finish was interrupted");
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';

// Imports the Google Cloud client library
const {Spanner, protos} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});
const instanceAdminClient = await spanner.getInstanceAdminClient();

// Updates an instance
try {
  const [operation] = await instanceAdminClient.updateInstance({
    instance: {
      name: instanceAdminClient.instancePath(projectId, instanceId),
      defaultBackupScheduleType:
        protos.google.spanner.admin.instance.v1.Instance
          .DefaultBackupScheduleType.AUTOMATIC, // optional
    },
    // Field mask specifying fields that should get updated in an Instance
    fieldMask: (protos.google.protobuf.FieldMask = {
      paths: ['default_backup_schedule_type'],
    }),
  });

  await operation.promise();
  const [metadata] = await instanceAdminClient.getInstance({
    name: instanceAdminClient.instancePath(projectId, instanceId),
  });
  console.log(
    `Instance ${instanceId} has been updated with the ${metadata.defaultBackupScheduleType}` +
      ' default backup schedule type.',
  );
} catch (err) {
  console.error('ERROR:', err);
}

Python

如要瞭解如何安裝及使用 Spanner 的用戶端程式庫,請參閱「Spanner 用戶端程式庫」。

如要向 Spanner 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

def update_instance_default_backup_schedule_type(instance_id):
    spanner_client = spanner.Client()

    name = "{}/instances/{}".format(spanner_client.project_name, instance_id)

    operation = spanner_client.instance_admin_api.update_instance(
        instance=spanner_instance_admin.Instance(
            name=name,
            default_backup_schedule_type=spanner_instance_admin.Instance.DefaultBackupScheduleType.AUTOMATIC,  # Optional
        ),
        field_mask=field_mask_pb2.FieldMask(paths=["default_backup_schedule_type"]),
    )

    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)

    print("Updated instance {} to have default backup schedules".format(instance_id))

移動執行個體

如要瞭解如何將執行個體從任何執行個體設定移至任何其他執行個體設定 (包括在區域和多區域設定之間移動),請參閱「移動執行個體」。

刪除執行個體

您可以使用 Google Cloud 控制台或 gcloud CLI 刪除執行個體。

如要刪除的執行個體中,有一或多個資料庫已啟用防刪除功能,您必須先停用該執行個體中所有資料庫的防刪除功能,才能刪除執行個體。

控制台

  1. 前往 Google Cloud 控制台的「Spanner Instances」(Spanner 執行個體) 頁面。

    前往「Instances」(執行個體) 頁面

  2. 按一下您要刪除的執行個體名稱。

  3. 按一下 [Delete instance] (刪除執行個體)。

  4. 請按照操作說明來確認您要刪除的執行個體。

  5. 點選「刪除」。

gcloud

使用 gcloud spanner instances delete 指令,並將 INSTANCE_ID 替換為執行個體 ID:

gcloud spanner instances delete INSTANCE_ID

停止或重新啟動執行個體

Spanner 是全代管資料庫服務,可監控自身的基礎工作和資源,包括在必要時監控及重新啟動程序,且不會造成停機。由於不需要手動停止或重新啟動特定執行個體,Spanner 並未提供這類操作方式。

後續步驟