Criar uma instância de produção

Criar uma instância de produção no projeto atual.

Exemplo de código

C#

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

// Creates a production instance with "<intanceId>-prod" instance ID,
// with cluster ID "ssd-cluster1", 3 nodes and location us-east1-b.
displayName += " Prod"; // Display name is for display purposes only. It doesn't have to equal instanceId and can be amended after instance is created.
string instanceId = Regex.Replace(displayName, @"[^A-Za-z0-9_\.~]+", "-").ToLower();

// Please refer to the link below for the full list of available locations:
// https://cloud.google.com/bigtable/docs/locations
string zone1 = "us-east1-b";

// The instance to create.
Instance myInstance = new Instance
{
    DisplayName = displayName,
    // You can choose DEVELOPMENT or PRODUCTION type here.
    // If not set, will default to PRODUCTION type.
    // Instance type can be upgraded from DEVELOPMENT to PRODUCTION but cannot be dowgraded after the instance is created.
    Type = Instance.Types.Type.Production,
    Labels = { { "prod-label", "prod-label" } }
};

// The first cluster to be created within the instance.
Cluster myCluster1 = new Cluster
{
    // You can choose SSD or HDD storage type here: StorageType.Ssd or StorageType.Hdd.
    // Cluster storage type can not be changed after the instance is created.
    // If not set will default to SSD type.
    DefaultStorageType = StorageType.Ssd,
    LocationAsLocationName = new LocationName(projectId, zone1),
    // Serve Nodes count can only be set if PRODUCTION type instance is being created.
    // Minimum count of 3 serve nodes must be specified.
    // Serve Nodes count can be increased and decreased after an instance is created.
    ServeNodes = 3
};

// Initialize request argument(s).
CreateInstanceRequest request = new CreateInstanceRequest
{
    ParentAsProjectName = new ProjectName(projectId),
    Instance = myInstance,
    InstanceId = instanceId,
    // Must specify at lease one cluster.
    // Only PRODUCTION type instance can be created with more than one cluster.
    // Currently all clusters must have the same storage type.
    // Clusters must be set to different locations.
    Clusters = { { "ssd-cluster1", myCluster1 } }
};

try
{
    // Make a request.
    Operation<Instance, CreateInstanceMetadata> createInstanceResponse =
        bigtableInstanceAdminClient.CreateInstance(request);
    Console.WriteLine("Waiting for operation to complete...");

    // Poll until the returned long-running operation is complete
    Operation<Instance, CreateInstanceMetadata> completedResponse =
        createInstanceResponse.PollUntilCompleted();
}
catch (Exception ex)
{
    Console.WriteLine($"Exception while creating {displayName} instance");
    Console.WriteLine(ex.Message);
}

C++

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::future;
using ::google::cloud::StatusOr;
[](cbt::InstanceAdmin instance_admin, std::string const& instance_id,
   std::string const& zone) {
  std::string display_name("Put description here");
  std::string cluster_id = instance_id + "-c1";
  auto cluster_config = cbt::ClusterConfig(zone, 3, cbt::ClusterConfig::HDD);
  cbt::InstanceConfig config(instance_id, display_name,
                             {{cluster_id, cluster_config}});
  config.set_type(cbt::InstanceConfig::PRODUCTION);

  future<StatusOr<google::bigtable::admin::v2::Instance>> instance_future =
      instance_admin.CreateInstance(config);
  // Show how to perform additional work while the long running operation
  // completes. The application could use future.then() instead.
  std::cout << "Waiting for instance creation to complete " << std::flush;
  instance_future.wait_for(std::chrono::seconds(1));
  std::cout << '.' << std::flush;
  auto instance = instance_future.get();
  if (!instance) throw std::runtime_error(instance.status().message());
  std::cout << "DONE, details=" << instance->DebugString() << "\n";
}

Java

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

// Creates a Production Instance with the ID "ssd-instance",
// cluster id "ssd-cluster", 3 nodes and location "us-central1-f".
CreateInstanceRequest createInstanceRequest =
    CreateInstanceRequest.of(instanceId)
        .addCluster(clusterId, "us-central1-f", 3, StorageType.SSD)
        .setType(Instance.Type.PRODUCTION)
        .addLabel("department", "accounting");
// Creates a production instance with the given request.
try {
  Instance instance = adminClient.createInstance(createInstanceRequest);
  System.out.printf("PRODUCTION type instance %s created successfully%n", instance.getId());
} catch (Exception e) {
  System.err.println("Failed to create instance: " + e.getMessage());
  throw e;
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

// Creates a Production Instance with the ID "ssd-instance"
// with cluster id "ssd-cluster", 3 nodes and location us-central1-f

const instanceOptions = {
  clusters: [
    {
      id: clusterID,
      nodes: 3,
      location: 'us-central1-f',
      storage: 'ssd',
    },
  ],
  type: 'PRODUCTION', // Optional as default type is PRODUCTION
  labels: {'prod-label': 'prod-label'},
};

// Create production instance with given options
const [prodInstance] = await instance.create(instanceOptions);
console.log(`Created Instance: ${prodInstance.id}`);

PHP

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

use Google\Cloud\Bigtable\Admin\V2\Instance\Type as InstanceType;
use Google\Cloud\Bigtable\Admin\V2\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\StorageType;
use Google\Cloud\Bigtable\Admin\V2\Instance;
use Google\Cloud\Bigtable\Admin\V2\Cluster;
use Google\ApiCore\ApiException;

/**
 * Create a production Bigtable instance
 *
 * @param string $projectId The Google Cloud project ID
 * @param string $instanceId The ID of the Bigtable instance to be generated
 * @param string $clusterId The ID of the cluster to be generated
 * @param string $locationId The Bigtable region ID where you want your instance to reside
 */
function create_production_instance(
    string $projectId,
    string $instanceId,
    string $clusterId,
    string $locationId = 'us-east1-b'
): void {
    $instanceAdminClient = new BigtableInstanceAdminClient();

    $projectName = $instanceAdminClient->projectName($projectId);
    $instanceName = $instanceAdminClient->instanceName($projectId, $instanceId);

    $serveNodes = 3;
    $storageType = StorageType::SSD;
    $production = InstanceType::PRODUCTION;
    $labels = ['prod-label' => 'prod-label'];

    $instance = new Instance();
    $instance->setDisplayName($instanceId);

    $instance->setLabels($labels);
    $instance->setType($production);

    $cluster = new Cluster();
    $cluster->setDefaultStorageType($storageType);
    $locationName = $instanceAdminClient->locationName($projectId, $locationId);
    $cluster->setLocation($locationName);
    $cluster->setServeNodes($serveNodes);
    $clusters = [
        $clusterId => $cluster
    ];
    try {
        $instanceAdminClient->getInstance($instanceName);
        printf('Instance %s already exists.' . PHP_EOL, $instanceId);
        throw new Exception(sprintf('Instance %s already exists.' . PHP_EOL, $instanceId));
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            printf('Creating an Instance: %s' . PHP_EOL, $instanceId);
            $operationResponse = $instanceAdminClient->createInstance(
                $projectName,
                $instanceId,
                $instance,
                $clusters
            );
            $operationResponse->pollUntilComplete();
            if (!$operationResponse->operationSucceeded()) {
                print('Error: ' . $operationResponse->getError()->getMessage());
            } else {
                printf('Instance %s created.', $instanceId);
            }
        } else {
            throw $e;
        }
    }
}

Python

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

cluster = instance.cluster(
    cluster_id,
    location_id=location_id,
    serve_nodes=serve_nodes,
    default_storage_type=storage_type,
)
if not instance.exists():
    print("\nCreating an instance")
    # Create instance with given options
    operation = instance.create(clusters=[cluster])
    # Ensure the operation completes.
    operation.result(timeout=60)
    print("\nCreated instance: {}".format(instance_id))

Ruby

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

# instance_id      = "my-instance"
# cluster_id       = "my-cluster"
# cluster_location = "us-east1-b"
puts "Creating a PRODUCTION Instance"
job = bigtable.create_instance(
  instance_id,
  display_name: "Sample production instance",
  labels:       { "env": "production" },
  type:         :PRODUCTION # Optional as default type is :PRODUCTION
) do |clusters|
  clusters.add cluster_id, cluster_location, nodes: 3, storage_type: :SSD
end

job.wait_until_done!
instance = job.instance
puts "Created Instance: #{instance.instance_id}"

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte o navegador de exemplos do Google Cloud.