インスタンスを作成、管理する

このページでは、Spanner インスタンスを作成、一覧表示、編集、削除する方法について説明します。

インスタンスの作成

インスタンスは、 Google Cloud コンソール、Google Cloud CLI、またはクライアント ライブラリを使用して作成できます。オプションの読み取り専用レプリカを追加して、カスタム インスタンス構成のインスタンスを作成することもできます。

コンソール

  1. Google Cloud コンソールで、[Spanner インスタンス] ページに移動します。

  2. [インスタンスを作成] をクリックします。

    [インスタンスの作成] に移動

  3. [エディションを選択] セクションで、Spanner のエディションを選択します。

    異なるエディション間で仕様を比較する場合は、[エディションを比較] をクリックします。詳細については、Spanner エディションの概要をご覧ください。

  4. [続行] をクリックします。

  5. [インスタンス名の指定] セクションで、コンソールに表示するインスタンス名を入力します。 Google Cloud インスタンス名は、 Google Cloud プロジェクト内で一意である必要があります。

  6. インスタンス ID は、インスタンスを永続的に識別します。インスタンス ID は Google Cloud プロジェクト内で一意にする必要があります。インスタンス ID を後で変更することはできません。

  7. [続行] をクリックします。

  8. [インスタンスを構成する] セクションの [構成を選択] で、[リージョン]、[デュアルリージョン]、または [マルチリージョン] を選択します。

  9. プルダウンから構成のロケーションを選択します。

  10. 省略可: Spanner の基本構成に読み取り専用レプリカを追加するには、まず Google Cloud CLI を使用してカスタム インスタンス構成を作成します。基本構成にオプションの読み取り専用レプリカを追加できるのは、Enterprise エディションと Enterprise Plus エディションです。

  11. [続行] をクリックします。

  12. [コンピューティング容量を割り当てる] セクションの [単位を選択] で、次のいずれかをクリックします。

    • 大規模なインスタンスの場合: ノード。1 ノードは 1,000 個の処理ユニットに相当します。
    • 小規模なインスタンスの場合: 処理ユニット

    詳細については、コンピューティング容量、ノード、処理ユニットをご覧ください。

  13. [スケーリング モードを選択する] で、次のいずれかをクリックします。

    • [手動で割り当てる] を選択すると、固定されたコンピューティング リソースと費用に対してコンピューティング容量を手動で設定できます。

      • [数量] は、このインスタンスに使用する処理ユニットまたはノードの数を示します。
    • [自動スケーリング] を選択すると、Spanner がコンピューティング容量を自動的に追加、削除できるようにできます。Spanner Enterprise エディションと Enterprise Plus エディションでは、マネージド オートスケーラーを使用できます。マネージド オートスケーラーの詳細については、Spanner のマネージド オートスケーラーについての記事をご覧ください。次のマネージド オートスケーラー オプションを構成します。

      • [最小] は、コンピューティング容量に選択した測定単位に応じてスケールダウンする際の下限です。詳細については、下限を決定するをご覧ください。
      • [最大] は、コンピューティング容量に選択した測定単位に応じてスケールアップする最大制限です。詳細については、上限を決定するをご覧ください。
      • [優先度の高い CPU 使用率の目標値] は、優先度の高い CPU の目標使用率です。詳細については、CPU 使用率の目標値を決めるをご覧ください。
      • [ストレージ使用率の目標値] は、使用するストレージの目標使用率です。詳細については、CPU 使用率の目標値を決めるをご覧ください。
  14. 省略可: スケーリング モードとして [自動スケーリング] を選択した場合は、[非対称自動スケーリング オプションを表示する] プルダウンをクリックして、読み取り専用レプリカを他のレプリカとは別に自動スケーリングできます。詳細については、非対称読み取り専用自動スケーリングをご覧ください。

    1. 非対称に自動スケーリングする読み取り専用レプリカを選択します。

    2. 次の非対称オートスケーラー オプションを構成します。

      • [最小] は、コンピューティング容量に選択した測定単位に応じてスケールダウンする際の下限です。詳細については、下限を決定するをご覧ください。
      • [最大] は、コンピューティング容量に選択した測定単位に応じてスケールアップする最大制限です。詳細については、上限を決定するをご覧ください。
      • [優先度の高い CPU 使用率の目標値] は、優先度の高い CPU の目標使用率です。詳細については、CPU 使用率の目標値を決めるをご覧ください。
  15. [バックアップ] では、[デフォルトのバックアップ スケジュールを有効にする] チェックボックスがデフォルトでオンになっています。デフォルトのバックアップ スケジュールを無効にするには、チェックボックスをオフにします。有効の場合は、インスタンス内のすべての新しいデータベースに 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 を後で変更することはできません。
  • 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、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=CPU_PERCENTAGE \     --autoscaling-storage-target=STORAGE_PERCENTAGE \     [--asymmetric-autoscaling-option \        location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\        max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]

または

  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=CPU_PERCENTAGE \     --autoscaling-storage-target=STORAGE_PERCENTAGE \     [--asymmetric-autoscaling-option \        location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\        max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]

次のように置き換えます。

  • INSTANCE-ID: Google Cloud プロジェクト内で一意の永続的な識別子。インスタンス ID を後で変更することはできません。
  • INSTANCE-CONFIG: インスタンス構成の永続的な ID。インスタンスの地理的位置を定義し、データのレプリケート方法に影響します。カスタム インスタンス構成の場合は custom- で始まります。詳細については、インスタンス構成をご覧ください。
  • INSTANCE-DESCRIPTION: Google Cloud コンソールに表示されるインスタンスの名前。インスタンス名は、Google Cloud プロジェクト内で一意である必要があります。
  • MINIMUM_PROCESSING_UNITSMINIMUM_NODES: スケールダウン時の処理ユニットまたはノードの最小数。詳細については、下限を決定するをご覧ください。
  • MAXIMUM_PROCESSING_UNITSMAXIMUM_NODES: スケールアップ時の処理ユニットまたはノードの最大数。詳細については、上限を決定するをご覧ください。
  • CPU_PERCENTAGE: 使用する優先度の高い CPU の目標使用率を 10~90% で指定します。費用を最適化する場合は、より高い使用率を使用します。詳細については、CPU 使用率の目標値を決めるをご覧ください。
  • STORAGE_PERCENTAGE: 使用するストレージの目標使用率(10~99%)。詳細については、CPU 使用率の目標値を決めるをご覧ください。

オプションのフラグ:

  • --asymmetric-autoscaling-option: このフラグを使用して、非対称自動スケーリングを有効にします。次のパラメータを置き換えます。

    • ASYMMETRIC_AUTOSCALING_LOCATION: フラグを使用する場合は、このパラメータが必要です。非対称にスケーリングする読み取り専用リージョンのロケーションです。
    • ASYMMETRIC_AUTOSCALING_MIN: 省略可能なパラメータ。スケールダウン時のノードの最小数です。
    • ASYMMETRIC_AUTOSCALING_MAX: 省略可能なパラメータ。スケールアップ時のノードの最大数です。
    • ASYMMETRIC_CPU_TARGET: 省略可能なパラメータ。使用する優先度の高い CPU の割合を 10%~90% で指定します。費用を最適化する場合は、より高い使用率を使用します。

カスタム構成の使用例

基本リージョン インスタンス構成 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))  

Ruby

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 インスタンス] ページに移動します。

[Spanner インスタンス] ページに移動

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 インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. 調べるインスタンスの名前をクリックします。

  3. エディション タイプの横にある [アップグレード] をクリックします。

  4. [エディションのインスタンス] ページの [エディションを更新] で、インスタンスの新しい上位エディションを選択します。

  5. [保存] をクリックします。

gcloud

gcloud spanner instances update コマンドを使用して、インスタンスのエディションをアップグレードします。

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

次のように置き換えます。

  • INSTANCE_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 分で完了します。ダウンタイムはありません。

gcloud

gcloud spanner instances update コマンドを使用して、インスタンスのエディションをダウングレードします。

gcloud spanner instances update INSTANCE_ID --edition=EDITION

次のように置き換えます。

  • INSTANCE_ID: インスタンスの永続的な識別子。
  • EDITION: インスタンスの新しい下位エディションを指定します。詳細については、Spanner エディションの概要をご覧ください。

表示名を変更する

コンソール

  1. Google Cloud コンソールの [Spanner インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. 変更するインスタンスの名前をクリックします。

  3. [インスタンスの編集] をクリックします。

  4. 新しいインスタンス名を入力します。Google Cloud プロジェクト内で一意の名前を指定してください。

  5. [保存] をクリックします。

gcloud

gcloud spanner instances update コマンドを次のように使用します。

gcloud spanner instances update INSTANCE_ID --description=INSTANCE_NAME

次のように置き換えます。

  • INSTANCE_ID: インスタンスの永続的な識別子。
  • INSTANCE_NAME:Google Cloud コンソールに表示されるインスタンスの名前。インスタンス名は、Google Cloud プロジェクト内で一意である必要があります。

コンピューティング容量を変更する

CPU 使用率ストレージ使用率が推奨最大値を超えないように、十分なコンピューティング容量をプロビジョニングする必要があります。詳細については、Spanner の割り当てと上限をご覧ください。

次のシナリオを除き、Spanner インスタンスのコンピューティング容量を削減できます。

  • ノード(1,000 処理ユニット)あたり 10 TiB を超えるデータを保存することはできません。

  • インスタンスのデータに多数の分割があります。このシナリオでは、コンピューティング容量を削減した後に Spanner がスプリットを管理できない可能性があります。Cloud Spanner でインスタンスのすべてのスプリットを管理するのに必要な最小容量が見つかるまで、コンピューティング容量を徐々に減らすことができます。

    Spanner は、使用パターンに合わせて多数のスプリットを作成できます。使用パターンが変化すると、1 ~ 2 週間後に Spanner が一部のスプリットをマージし、インスタンスのコンピューティング容量を削減してみることができます。

コンピューティング容量を削除するときは、Cloud Monitoring で CPU 使用率とリクエスト レイテンシをモニタリングし、CPU 使用率がリージョンのインスタンスで 65% を、マルチリージョンのインスタンスの各リージョンで 45% を下回るようにしてください。コンピューティング容量の削除中に、リクエストのレイテンシが一時的に増加する場合があります。

インスタンスのコンピューティング容量を増やすには、コンピューティング容量を追加するだけの十分な割り当てがGoogle Cloud プロジェクトに必要です。完了するまでの時間は、増加リクエストのサイズによって異なります。ほとんどの場合、リクエストは数分以内に完了します。まれに、スケールアップが完了するまでに最大 1 時間かかることがあります。

コンソール

  1. Google Cloud コンソールの [Spanner インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. 変更するインスタンスの名前をクリックします。

  3. [インスタンスの編集] をクリックします。

  4. コンピューティング容量を変更するには、測定単位(処理ユニットまたはノード)を選択し、数量を入力します。処理ユニットを使用する場合は、1,000 までの数量については 100 の倍数(100、200、300 など)を、それよりも多い数量については 1,000 の倍数(1,000、2,000、3,000 など)を入力します。各ノードは 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: インスタンスの永続的な識別子。
  • NODE_COUNT: ノード数で表されるインスタンスのコンピューティング容量。各ノードは 1,000 の処理ユニットに相当します。
  • PROCESSING_UNIT_COUNT: 処理ユニット数で表されるインスタンスのコンピューティング容量。1,000 までの数量については 100 の倍数(100、200、300 など)を、それより多い数量については 1,000 の倍数(1,000、2,000、3,000 など)を入力します。

オプションのフラグ:

  • --async: このフラグは、処理中のオペレーションの完了を待たず、すぐにリクエストを返す場合に使用します。リクエストのステータスを確認するには、gcloud spanner operations describe を実行します。

インスタンスのマネージド オートスケーラーを有効にするか、変更する

Spanner インスタンスの自動スケーリングを有効または変更するには、 Google Cloud コンソール、gcloud CLI、または Spanner クライアント ライブラリを使用します。既存のインスタンスにマネージド オートスケーリング機能を追加する、または変更する場合は、次の制限が適用されます。

  • マネージド オートスケーラーは、Enterprise エディションまたは Enterprise Plus エディションでのみ使用できます。
  • 移動するインスタンスでマネージド オートスケーラーを有効にすることはできません。
  • マネージド オートスケーラーが有効になっている間は、インスタンスを移動できません。

コンソール

  1. Google Cloud コンソールの [Spanner インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. マネージド オートスケーラーを有効にするインスタンスの名前をクリックします。

  3. [インスタンスの編集] をクリックします。

  4. [コンピューティング容量を構成する] で、[自動スケーリング] をクリックします。

  5. [最小] に、スケールダウン時に使用する下限を選択します。詳細については、下限を決定するをご覧ください。

  6. [最大] で、スケールアップ時に使用する上限を選択します。詳細については、上限を決定するをご覧ください。

  7. [優先度の高い CPU 使用率の目標値] で、使用する優先度の高い CPU の割合を選択します。詳細については、CPU 使用率の目標値を決めるをご覧ください。

  8. [ストレージ使用率の目標値] で、使用するストレージの割合を選択します。詳細については、CPU 使用率の目標値を決めるをご覧ください。

  9. 省略可: スケーリング モードとして [自動スケーリング] を選択した場合は、[非対称自動スケーリング オプションを表示する] プルダウンをクリックして、読み取り専用レプリカを他のレプリカとは別に自動スケーリングできます。

    1. 非対称に自動スケーリングする読み取り専用レプリカを選択します。

    2. 次のオートスケーラー オプションを構成します。

      • [最小] は、コンピューティング容量に選択した測定単位に応じてスケールダウンする際の下限です。詳細については、下限を決定するをご覧ください。
      • [最大] は、コンピューティング容量に選択した測定単位に応じてスケールアップする最大制限です。詳細については、上限を決定するをご覧ください。
      • [優先度の高い CPU 使用率の目標値] は、優先度の高い CPU の目標使用率です。詳細については、CPU 使用率の目標値を決めるをご覧ください。
  10. [保存] をクリックします。

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=CPU_PERCENTAGE \     --autoscaling-storage-target=STORAGE_PERCENTAGE \     [--asymmetric-autoscaling-option \        location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\        max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]

または

  gcloud spanner instances update INSTANCE_ID \     --autoscaling-min-processing-units=MINIMUM_NODES \     --autoscaling-max-processing-units=MAXIMUM_NODES \     --autoscaling-high-priority-cpu-target=CPU_PERCENTAGE \     --autoscaling-storage-target=STORAGE_PERCENTAGE \     [--asymmetric-autoscaling-option \        location=ASYMMETRIC_AUTOSCALING_LOCATION,min_nodes=ASYMMETRIC_AUTOSCALING_MIN,\        max_nodes=ASYMMETRIC_AUTOSCALING_MAX,high_priority_cpu_target=ASYMMETRIC_CPU_TARGET]

次のように置き換えます。

  • INSTANCE_ID: インスタンスの永続的な識別子。
  • MINIMUM_PROCESSING_UNITSMINIMUM_NODES: スケールダウン時に使用する処理ユニットまたはノードの最小数。詳細については、下限を決定するをご覧ください。
  • MAXIMUM_PROCESSING_UNITSMAXIMUM_NODES: スケールアップ時に使用する処理ユニットまたはノードの最大数。詳細については、上限を決定するをご覧ください。
  • CPU_PERCENTAGE: 使用する優先度の高い CPU の割合を 10%~90% で指定します。費用を最適化する必要があり、すべてのリクエストで低レイテンシを必要としない場合は、より高い割合を使用します。詳細については、CPU 使用率の目標値を決めるをご覧ください。
  • STORAGE_PERCENTAGE: 使用するストレージの目標割合(10%~99%)。詳細については、CPU 使用率の目標値を決めるをご覧ください。

オプションのフラグ:

  • --asymmetric-autoscaling-option: このフラグを使用して、非対称自動スケーリングを有効にします。次のパラメータを置き換えます。

    • ASYMMETRIC_AUTOSCALING_LOCATION: フラグを使用する場合は、このパラメータが必要です。非対称にスケーリングする読み取り専用リージョンのロケーションです。
    • ASYMMETRIC_AUTOSCALING_MIN: 省略可能なパラメータ。スケールダウン時のノードの最小数です。
    • ASYMMETRIC_AUTOSCALING_MAX: 省略可能なパラメータ。スケールアップ時のノードの最大数です。
    • ASYMMETRIC_CPU_TARGET: 省略可能なパラメータ。使用する優先度の高い CPU の割合を 10%~90% で指定します。費用を最適化する場合は、より高い使用率を使用します。

マネージド オートスケーラーをインスタンスに追加した後で、マネージド オートスケーラーの設定を変更することもできます。たとえば、処理ユニットの最大数を 10,000 に増やす場合は、次のコマンドを実行します。

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

インスタンスをマネージド オートスケーラーを使用する状態から手動スケーリングに変更する

Spanner インスタンスで手動スケーリングとマネージド スケーリングのどちらを使用するかは、 Google Cloud コンソール、gcloud CLI、または Spanner クライアント ライブラリを使用して変更できます。

コンソール

  1. Google Cloud コンソールの [Spanner インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. マネージド オートスケーラーを無効にするインスタンスの名前をクリックします。

  3. [スケーリング モードを選択する] で [手動で割り当てる] をクリックします。

  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: インスタンスの永続的な識別子。
  • NODE_COUNT: ノード数で表されるインスタンスのコンピューティング容量。各ノードは 1,000 の処理ユニットに相当します。
  • PROCESSING_UNIT_COUNT: 処理ユニット数で表されるインスタンスのコンピューティング容量。1,000 までの数量については 100 の倍数(100、200、300 など)を、それより多い数量については 1,000 の倍数(1,000、2,000、3,000 など)を入力します。

インスタンスにラベルを付ける

ラベルはリソースを整理するのに役立ちます。

コンソール

  1. Google Cloud コンソールの [Spanner インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. インスタンスのチェックボックスをオンにします。ページの右側に情報パネルが表示されます。

  3. [情報パネル] で [ラベル] タブをクリックします。これで、Spanner インスタンスのラベルを追加、削除、または更新できるようになります。

デフォルトのバックアップ スケジュールの種類を編集する

新しいすべてのインスタンスでは、デフォルトのバックアップ スケジュールが自動的に有効になります。インスタンスのデフォルトのバックアップ スケジュールは、インスタンスの作成時、または後でインスタンスを編集するときに有効または無効にできます。詳細については、デフォルトのバックアップ スケジュールをご覧ください。

コンソール

  1. Google Cloud コンソールの [Spanner インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. デフォルトのバックアップ スケジュールを編集するインスタンスの名前をクリックします。

  3. [インスタンスの編集] をクリックします。

  4. [バックアップ] の [デフォルトのバックアップ スケジュールを有効にする] チェックボックスで、デフォルトのバックアップ スケジュールが有効かどうか確認できます。有効な場合は、このインスタンス内のすべての新しいデータベースにデフォルトのバックアップ スケジュールが作成されます。

  5. [保存] をクリックします。

gcloud

gcloud spanner instances update コマンドを使用して、デフォルトのバックアップ スケジュールのタイプを編集します。

デフォルトのバックアップ スケジュール タイプを編集するには、次のコマンドを実行します。

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

次のように置き換えます。

  • INSTANCE_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 コンソールまたは Google Cloud CLI を使用します。

削除保護が有効になっているデータベースが 1 つ以上存在するインスタンスを削除するには、まずそのインスタンスのすべてのデータベースで削除保護を無効にする必要があります。

コンソール

  1. Google Cloud コンソールの [Spanner インスタンス] ページに移動します。

    [Spanner インスタンス] ページに移動

  2. 削除するインスタンスの名前をクリックします。

  3. [インスタンスの削除] をクリックします。

  4. 指示に従って、インスタンスを削除することを確認します。

  5. [削除] をクリックします。

gcloud

gcloud spanner instances delete コマンドを使用します。INSTANCE_ID の部分はインスタンス ID で置き換えてください。

gcloud spanner instances delete INSTANCE_ID

インスタンスを停止または再起動する

Spanner はフルマネージド データベース サービスであり、独自の基本的なタスクやリソースを監視します。この際、プロセスのモニタリングや、ダウンタイムのない再起動も必要に応じて行われます。特定のインスタンスを手動で停止または再起動する必要がないため、Spanner にはそのための手段は用意されていません。

次のステップ