Esta página foi traduzida pela API Cloud Translation.
Switch to English

Criar instância

Cria uma instância.

Exemplo de código

C#

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud 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;
    }
}

C++

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud Spanner.

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

  std::string region_id = region.empty() ? "us-central1" : region;
  std::string instance_config =
      "projects/" + project_id + "/instanceConfigs/regional-" + region_id;
  auto instance =
      client
          .CreateInstance(
              spanner::CreateInstanceRequestBuilder(in, instance_config)
                  .SetDisplayName(display_name)
                  .SetNodeCount(1)
                  .SetLabels({{"cloud_spanner_samples", "true"}})
                  .Build())
          .get();
  if (!instance) throw std::runtime_error(instance.status().message());
  std::cout << "Created instance [" << in << "]\n";
}

Go

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud 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 {
	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: %v", 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: %v", 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
}

Java

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud Spanner.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.spanner.Instance;
import com.google.cloud.spanner.InstanceAdminClient;
import com.google.cloud.spanner.InstanceConfigId;
import com.google.cloud.spanner.InstanceId;
import com.google.cloud.spanner.InstanceInfo;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.spanner.admin.instance.v1.CreateInstanceMetadata;
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) {
    Spanner spanner = SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
    InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();

    // Set Instance configuration.
    String configId = "regional-us-central1";
    int nodeCount = 2;
    String displayName = "Descriptive name";

    // Create an InstanceInfo object that will be used to create the instance.
    InstanceInfo instanceInfo =
        InstanceInfo.newBuilder(InstanceId.of(projectId, instanceId))
            .setInstanceConfigId(InstanceConfigId.of(projectId, configId))
            .setNodeCount(nodeCount)
            .setDisplayName(displayName)
            .build();
    OperationFuture<Instance, CreateInstanceMetadata> operation =
        instanceAdminClient.createInstance(instanceInfo);
    try {
      // Wait for the createInstance operation to finish.
      Instance instance = operation.get();
      System.out.printf("Instance %s was successfully created%n", instance.getId());
    } catch (ExecutionException e) {
      System.out.printf(
          "Error: Creating instance %s failed with error message %s%n",
          instanceInfo.getId(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud Spanner.

// Imports the Google Cloud client library
const {Spanner} = 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 instance = spanner.instance(instanceId);

// Creates a new instance
try {
  console.log(`Creating instance ${instance.formattedName_}.`);
  const [, operation] = await instance.create({
    config: 'regional-us-central1',
    nodes: 1,
    displayName: 'This is a display name.',
    labels: {
      ['cloud_spanner_samples']: 'true',
    },
  });

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

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

PHP

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud Spanner.

use Google\Cloud\Spanner\SpannerClient;

/**
 * Creates an instance.
 * Example:
 * ```
 * create_instance($instanceId);
 * ```
 *
 * @param string $instanceId The Spanner instance ID.
 */
function create_instance($instanceId)
{
    $spanner = new SpannerClient();
    $instanceConfig = $spanner->instanceConfiguration(
        'regional-us-central1'
    );
    $operation = $spanner->createInstance(
        $instanceConfig,
        $instanceId,
        [
            'displayName' => 'This is a display name.',
            'nodeCount' => 1,
            'labels' => [
                'cloud_spanner_samples' => true,
            ]
        ]
    );

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

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

Python

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud Spanner.

def create_instance(instance_id):
    """Creates an instance."""
    spanner_client = spanner.Client()

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

    instance = spanner_client.instance(
        instance_id,
        configuration_name=config_name,
        display_name="This is a display name.",
        node_count=1,
    )

    operation = instance.create()

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

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

Ruby

Para saber como instalar e usar a biblioteca de cliente do Cloud Spanner, consulte as bibliotecas de cliente do Cloud Spanner.

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

require "google/cloud/spanner"

spanner  = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id

job = spanner.create_instance instance_id,
                              name:   instance_id,
                              config: "regional-us-central1",
                              nodes:  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