Criar um cluster

Criar um cluster no projeto atual de acordo com o código de instância.

Exemplo de código

C++

Para aprender a instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

namespace cbt = ::google::cloud::bigtable;
namespace cbta = ::google::cloud::bigtable_admin;
using ::google::cloud::future;
using ::google::cloud::Location;
using ::google::cloud::Project;
using ::google::cloud::StatusOr;
[](cbta::BigtableInstanceAdminClient instance_admin,
   std::string const& project_id, std::string const& instance_id,
   std::string const& cluster_id, std::string const& zone) {
  auto const project = Project(project_id);
  std::string instance_name = cbt::InstanceName(project_id, instance_id);

  google::bigtable::admin::v2::Cluster c;
  c.set_location(Location(project, zone).FullName());
  c.set_serve_nodes(3);
  c.set_default_storage_type(google::bigtable::admin::v2::HDD);

  future<StatusOr<google::bigtable::admin::v2::Cluster>> cluster_future =
      instance_admin.CreateCluster(instance_name, cluster_id, std::move(c));

  // Applications can wait asynchronously, in this example we just block.
  auto cluster = cluster_future.get();
  if (!cluster) throw std::move(cluster).status();
  std::cout << "Successfully created cluster " << cluster->name() << "\n";
}

C#

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

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

// Create an additional cluster with cluster id "ssd-cluster2" with 3 nodes and location us-east1-d.
// Additional cluster can only be created in PRODUCTION type instance.
// Additional cluster must have same storage type as existing cluster.
// Please read about routing_policy for more information on mutli cluster instances.
// https://cloud.google.com/bigtable/docs/reference/admin/rpc/google.bigtable.admin.v2#google.bigtable.admin.v2.AppProfile.MultiClusterRoutingUseAny
// Cluster to be created within the instance.
Cluster myCluster2 = new Cluster
{
    DefaultStorageType = StorageType.Ssd,
    LocationAsLocationName = new LocationName(projectId, zone2),
    ServeNodes = 3
};
// Initialize request argument(s).
CreateClusterRequest request = new CreateClusterRequest
{
    ParentAsInstanceName = new InstanceName(projectId, instanceId),
    ClusterId = "ssd-cluster2",
    Cluster = myCluster2
};
try
{
    // Make the request
    Console.WriteLine("Waiting for operation to complete...");
    Operation<Cluster, CreateClusterMetadata> response = bigtableInstanceAdminClient.CreateCluster(request);
    // Poll until the returned long-running operation is complete
    Operation<Cluster, CreateClusterMetadata> completedResponse = response.PollUntilCompleted();

}
catch (Exception ex)
{
    Console.WriteLine($"Exception creating additional cluster {request.ClusterId} in instance {instanceId}");
    Console.WriteLine(ex.Message);
}

Java

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

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

try {
  adminClient.createCluster(
      CreateClusterRequest.of(instanceId, CLUSTER)
          .setZone("us-central1-c")
          .setServeNodes(3)
          .setStorageType(StorageType.SSD));
  System.out.printf("Cluster: %s created successfully%n", CLUSTER);
} catch (AlreadyExistsException e) {
  System.err.println("Failed to add cluster, already exists: " + e.getMessage());
}

Node.js

Para aprender a instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

const clusterOptions = {
  location: 'us-central1-c',
  nodes: 3,
  storage: 'ssd',
};

const [cluster, operation] = await instance.createCluster(
  clusterID,
  clusterOptions
);
await operation.promise();
console.log(`Cluster created: ${cluster.id}`);

PHP

Para aprender a instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

use Google\ApiCore\ApiException;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\Cluster;
use Google\Cloud\Bigtable\Admin\V2\CreateClusterRequest;
use Google\Cloud\Bigtable\Admin\V2\GetClusterRequest;
use Google\Cloud\Bigtable\Admin\V2\GetInstanceRequest;
use Google\Cloud\Bigtable\Admin\V2\ListClustersRequest;
use Google\Cloud\Bigtable\Admin\V2\StorageType;

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

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

    printf('Adding Cluster to Instance %s' . PHP_EOL, $instanceId);
    try {
        $getInstanceRequest = (new GetInstanceRequest())
            ->setName($instanceName);
        $instanceAdminClient->getInstance($getInstanceRequest);
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            printf('Instance %s does not exists.' . PHP_EOL, $instanceId);
            return;
        } else {
            throw $e;
        }
    }
    printf('Listing Clusters:' . PHP_EOL);

    $storage_type = StorageType::SSD;
    $serve_nodes = 3;
    $listClustersRequest = (new ListClustersRequest())
        ->setParent($instanceName);

    $clustersBefore = $instanceAdminClient->listClusters($listClustersRequest)->getClusters();
    $clusters = $clustersBefore->getIterator();
    foreach ($clusters as $cluster) {
        print($cluster->getName() . PHP_EOL);
    }

    $cluster = new Cluster();
    $cluster->setServeNodes($serve_nodes);
    $cluster->setDefaultStorageType($storage_type);
    $cluster->setLocation(
        $instanceAdminClient->locationName(
            $projectId,
            $locationId
        )
    );
    try {
        $getClusterRequest = (new GetClusterRequest())
            ->setName($clusterName);
        $instanceAdminClient->getCluster($getClusterRequest);
        printf('Cluster %s already exists, aborting...', $clusterId);
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            $createClusterRequest = (new CreateClusterRequest())
                ->setParent($instanceName)
                ->setClusterId($clusterId)
                ->setCluster($cluster);
            $operationResponse = $instanceAdminClient->createCluster($createClusterRequest);

            $operationResponse->pollUntilComplete();
            if ($operationResponse->operationSucceeded()) {
                $result = $operationResponse->getResult();
                printf('Cluster created: %s', $clusterId);
            } else {
                $error = $operationResponse->getError();
                printf('Cluster not created: %s', $error?->getMessage());
            }
        } else {
            throw $e;
        }
    }
}

Python

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

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

print("\nListing clusters...")
for cluster in instance.list_clusters()[0]:
    print(cluster.cluster_id)
cluster = instance.cluster(
    cluster_id,
    location_id=location_id,
    serve_nodes=serve_nodes,
    default_storage_type=storage_type,
)
if cluster.exists():
    print("\nCluster not created, as {} already exists.".format(cluster_id))
else:
    operation = cluster.create()
    # Ensure the operation completes.
    operation.result(timeout=480)
    print("\nCluster created: {}".format(cluster_id))

Ruby

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

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

# cluster_id       = "my-cluster"
# cluster_location = "us-east1-b"
job = instance.create_cluster(
  cluster_id,
  cluster_location,
  nodes:        3,
  storage_type: :SSD
)

job.wait_until_done!
cluster = job.cluster

A seguir

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