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

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

インスタンスを作成する

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

Console

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

    インスタンスの作成

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

  3. インスタンスを永続的に識別するためのインスタンス ID を入力します。インスタンス ID も Google Cloud プロジェクト内で一意にする必要があります。インスタンス ID は後で変更できません。

  4. [構成を選択] で、[リージョン] または [マルチリージョン] をクリックします。また、2 つのリージョン間で仕様を比較する場合は、[リージョン構成の比較] をクリックします。

  5. プルダウンから構成を選択します。

  6. 省略可: 読み取り専用レプリカを追加して読み取りをスケーリングし、低レイテンシのステイル読み取りをサポートします。読み取り専用レプリカを作成し、Google Cloud コンソールを使用してインスタンス構成に追加すると、カスタム インスタンス構成が自動的に作成されます。読み取り専用レプリカを追加する手順は次のとおりです。

    1. [読み取り専用レプリカの構成] を展開します。

    2. [読み取り専用レプリカを追加] をクリックします。

    3. リージョンと番号を選択します。

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

    • 小規模なインスタンスなら [処理ユニット]。
    • 大規模なインスタンスなら [Nodes]。ノードは 1,000 処理ユニットです。

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

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

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

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

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

gcloud

gcloud spanner instances create コマンドを使用して、インスタンスを作成します。インスタンスに必要なノードや処理ユニットの数としてコンピューティング容量を指定します。

gcloud spanner instances create INSTANCE-ID \
--config=INSTANCE-CONFIG \
--description=INSTANCE-DESCRIPTION \
--nodes=NODE-COUNT

または

gcloud spanner instances create INSTANCE-ID \
--config=INSTANCE-CONFIG \
--description=INSTANCE-DESCRIPTION \
--processing-units=PROCESSING-UNIT-COUNT

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

  • INSTANCE-ID: Google Cloud プロジェクト内で一意の永続的な識別子。インスタンス ID は後で変更できません。
  • INSTANCE-CONFIG: インスタンス構成の永続的な識別子。インスタンスの地理的位置を定義し、データのレプリケート方法に影響を与えます。カスタム インスタンス構成では、custom- で始まります。詳しくは、インスタンス構成をご覧ください。
  • INSTANCE-DESCRIPTION: Google Cloud コンソールに表示されるインスタンスの名前。インスタンス名は、Google Cloud プロジェクト内で一意である必要があります。
  • NODE-COUNT: ノード数で表されるインスタンスのコンピューティング容量。各ノードは 1,000 の処理ユニットに相当します。

  • PROCESSING-UNIT-COUNT: 処理ユニット数で表されるインスタンスのコンピューティング容量。1,000 までの数量については 100 の倍数(100、200、300 など)を、それより多い数量については 1,000 の倍数(1,000、2,000、3,000 など)を入力します。注: 後でマネージド オートスケーラーで有効にするインスタンスを作成する場合は、このパラメータを使用しないでください。

マネージド自動スケーリングを追加する(プレビュー

マネージド自動スケーリングを使用するように新しいインスタンスを構成するには、gcloud beta spanner instances create コマンドを使用します。詳細については、Spanner のマネージド オートスケーラーをご覧ください。

次のコマンドを使用して、マネージド オートスケーラーを使用するインスタンスを作成します。

  gcloud beta spanner instances create INSTANCE-ID \
    --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

または

  gcloud beta spanner instances create INSTANCE-ID \
    --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

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

  • INSTANCE-ID: Google Cloud プロジェクト内で一意の永続的な識別子。インスタンス ID は後で変更できません。
  • INSTANCE-CONFIG: インスタンス構成の永続的な識別子。インスタンスの地理的位置を定義し、データのレプリケート方法に影響を与えます。カスタム インスタンス構成では、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%)。詳細については、ストレージ使用率の目標値を決定するをご覧ください。

カスタム構成の使用例

基本リージョン インスタンス構成 us-central1 でインスタンス test-instance を作成するには、次のコマンドを実行します。

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

カスタム マルチリージョン インスタンス構成 custom-eur6 でインスタンス custom-eur6-instance を作成するには、まずカスタム インスタンス構成を作成します。

次のコマンドを実行します。

  gcloud spanner instances create custom-eur6-instance --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;

public class CreateInstanceSample
{
    public Instance CreateInstance(string projectId, string instanceId)
    {
        // Create the InstanceAdminClient instance.
        InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();

        // 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" },
            }
        };
        ProjectName projectName = ProjectName.FromProject(projectId);

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

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

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

        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"
	instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1"
)

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"},
		},
	})
	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"},
		},
	})
	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
}

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)
            .setNodeCount(nodeCount)
            .setConfig(
                InstanceConfigName.of(projectId, "regional-us-central1").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 java.util.concurrent.ExecutionException;

class CreateInstanceWithAutoscalingConfigExample {

  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 = "regional-us-central1";
      String displayName = "Descriptive name";

      // Create an autoscaling config.
      // When autoscaling_config is enabled, node_count and processing_units fields
      // need not be specified.
      AutoscalingConfig autoscalingConfig =
          AutoscalingConfig.newBuilder()
              .setAutoscalingLimits(
                  AutoscalingConfig.AutoscalingLimits.newBuilder().setMinNodes(1).setMaxNodes(2))
              .setAutoscalingTargets(
                  AutoscalingConfig.AutoscalingTargets.newBuilder()
                      .setHighPriorityCpuUtilizationPercent(65)
                      .setStorageUtilizationPercent(95))
              .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("Autoscaler 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");
      }
    }
  }
}

Node.js

Spanner 用のクライアント ライブラリをインストールして使用する方法については、Spanner クライアント ライブラリをご覧ください。

Spanner への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


// Imports the Google Cloud client library
const {Spanner} = 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
      },
    },
  });

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

  console.log(`Created instance ${instanceId}.`);
} 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())),
            },
        ),
    )

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

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

Ruby

Spanner 用のクライアント ライブラリをインストールして使用する方法については、Spanner クライアント ライブラリをご覧ください。

Spanner への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

# project_id  = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance 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: "regional-us-central1"

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 インスタンスのリストを表示できます。

Console

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

インスタンス ページに移動

Google Cloud コンソールには、Spanner インスタンスのリスト、各インスタンスの ID、表示名、構成、処理ユニットとノードの両方で表されたコンピューティング容量が表示されます。

gcloud

gcloud spanner instances list コマンドを使用します。

gcloud spanner instances list

gcloud CLI によって、各インスタンスの ID、表示名、構成、コンピューティング容量とともに Spanner インスタンスの一覧が出力されます。

インスタンスの編集

以降のセクションでは、インスタンスの表示名とコンピューティング容量を変更する方法について説明します。インスタンス ID やインスタンス構成は変更できません。

表示名を変更する

Console

  1. Google Cloud コンソールで、[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 の割り当てと上限をご覧ください。

既存のインスタンスのコンピューティング容量を削減できない場合があります。

  • コンピューティング容量を削除するには、1,000 処理ユニット(1 ノード)あたり 4 TB を超えるデータをインスタンスに格納する必要があります。
  • 過去の使用パターンに基づいて、Spanner はインスタンスのデータのスプリットを多数作成しました。まれにコンピューティング容量を削除した後はスプリットを管理できないことがあります。

後者の場合、Cloud Spanner でインスタンスのすべてのスプリットを管理するのに必要な最小容量が見つかるまで、コンピューティング容量を徐々に減らすことができます。使用パターンの変化により、インスタンスでそれほど多くのスプリットが必要なくなった場合、Cloud Spanner は最終的に一部のスプリットをマージし、1 ~ 2 週間後にインスタンスのコンピューティング容量を削減してみることができます。

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

インスタンスのコンピューティング容量を増やすには、コンピューティング容量を追加するだけの十分な割り当てが Google Cloud プロジェクトに必要です。

Console

  1. Google Cloud コンソールで、[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

または

gcloud spanner instances update INSTANCE-ID
--processing-units=PROCESSING-UNIT-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 インスタンス] ページに移動します。

    インスタンス ページに移動

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

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

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

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

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

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

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

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

gcloud

gcloud beta spanner instances update コマンドを使用して、マネージド オートスケーラーをインスタンスに追加します。詳細と制限事項については、Google Cloud CLI のフラグと制限事項をご覧ください。

マネージド オートスケーラーは、次のコマンドで追加できます。

  gcloud beta spanner instances update \
    --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

または

  gcloud beta spanner instances update \
    --autoscaling-min-processing-units=MINIMUM_NODES \
    --autoscaling-max-processing-units=MAXIMUM_NODES \
    --autoscaling-high-priority-cpu-target=CPU_PERCENTAGE \
    --autoscaling-storage-target=STORAGE_PERCENTAGE

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

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

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

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

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

コンソール

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

    インスタンス ページに移動

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

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

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

gcloud

gcloud beta spanner instances update コマンドを使用してデータセットを更新します。

次のコマンドを使用して、インスタンスをマネージド オートスケーラーから手動スケーリングに変更します。

  gcloud beta spanner instances update \
  --processing-units=PROCESSING-UNITS-COUNT

または

  gcloud beta spanner instances update \
  --nodes=NODE-COUNT

PROCESSING-UNIT-COUNT または NODE-COUNT を、インスタンスで使用する処理ユニットまたはノードの数に置き換えます。

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

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

Console

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

    インスタンス ページに移動

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

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

インスタンスを移動する

インスタンスをインスタンス構成から他のインスタンス構成(リージョン構成とマルチリージョン構成を含む)に移動する方法については、インスタンスを移動するをご覧ください。

インスタンスを削除する

インスタンスを削除するには、Google Cloud コンソールまたは Google Cloud CLI を使用します。

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

コンソール

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

    インスタンス ページに移動

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

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

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

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

gcloud

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

gcloud spanner instances delete INSTANCE-ID

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

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

次のステップ