הצגת רשימה של מכונות

הצגת רשימה של המכונות בפרויקט הנוכחי.

המשך למידה

לקבלת הסבר מפורט שכולל את דוגמת הקוד הזו, קראו את המאמר:

דוגמת קוד

C++

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

namespace cbta = ::google::cloud::bigtable_admin;
using ::google::cloud::Project;
using ::google::cloud::StatusOr;
[](cbta::BigtableInstanceAdminClient instance_admin,
   std::string const& project_id) {
  std::string project_name = Project(project_id).FullName();
  StatusOr<google::bigtable::admin::v2::ListInstancesResponse> instances =
      instance_admin.ListInstances(project_name);
  if (!instances) throw std::move(instances).status();
  for (auto const& instance : instances->instances()) {
    std::cout << instance.name() << "\n";
  }
  if (!instances->failed_locations().empty()) {
    std::cout << "The Cloud Bigtable service reports that the following "
                 "locations are temporarily unavailable and no information "
                 "about instances in these locations can be obtained:\n";
    for (auto const& failed_location : instances->failed_locations()) {
      std::cout << failed_location << "\n";
    }
  }
}

C#

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Lists instances in the project.
// Initialize request argument(s).
ListInstancesRequest listInstancesRequest = new ListInstancesRequest
{
    ParentAsProjectName = new ProjectName(projectId)
};
try
{
    // Make a request.
    Console.WriteLine("Waiting for operation to complete...");
    ListInstancesResponse instances = bigtableInstanceAdminClient.ListInstances(listInstancesRequest);
}
catch (Exception ex)
{
    Console.WriteLine($"Exception while requesting information about instances in {projectId} project");
    Console.WriteLine(ex.Message);
    return -1;
}
Console.WriteLine(new string('-', 50));

Go

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	bigtableadmin "cloud.google.com/go/bigtable/admin/apiv2"
	bigtableadminpb "google.golang.org/genproto/googleapis/bigtable/admin/v2"
)

// listInstances lists Cloud Bigtable instances in a project.
func listInstances(ctx context.Context, w io.Writer, projectID string) error {
	parent := fmt.Sprintf("projects/%s", projectID)

	client, err := bigtableadmin.NewBigtableInstanceAdminClient(ctx)
	if err != nil {
		return fmt.Errorf("NewBigtableInstanceAdminClient failed: %w", err)
	}
	defer client.Close()

	req := &bigtableadminpb.ListInstancesRequest{
		Parent: parent,
	}

	resp, err := client.ListInstances(ctx, req)
	if err != nil {
		return fmt.Errorf("ListInstances failed: %w", err)
	}

	for _, instance := range resp.GetInstances() {
		fmt.Fprintf(w, "Instance: %s\n", instance.GetName())
	}

	return nil
}

Java

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

try {
  String parent = "projects/" + projectId;
  ListInstancesRequest request = ListInstancesRequest.newBuilder().setParent(parent).build();
  ListInstancesResponse response = adminClient.listInstances(request);
  for (Instance instance : response.getInstancesList()) {
    System.out.println(instance.getName());
  }
} catch (Exception e) {
  System.err.println("Failed to list instances: " + e.getMessage());
}

Node.js

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

'use strict';

const {v2} = require('@google-cloud/bigtable');
const {BigtableInstanceAdminClient} = v2;
const {status} = require('@grpc/grpc-js');

const client = new BigtableInstanceAdminClient();

/**
 * Lists Bigtable instances in a Google Cloud project.
 *
 * @param {string} projectId - The Google Cloud project ID.
 */
async function listInstances(projectId) {
  try {
    const parent = `projects/${projectId}`;
    const [instances] = await client.listInstances({
      parent,
    });

    const instanceList = Array.isArray(instances)
      ? instances
      : instances?.instances || [];

    for (const instance of instanceList) {
      console.log(`Instance: ${instance.name}`);
      console.log(`Display name: ${instance.displayName}`);
      console.log(`State: ${instance.state}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      console.error(`Failed to list instances: ${err.message}`);
    }
  }
}

module.exports = {listInstances};

PHP

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Bigtable\Admin\V2\Client\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\ListInstancesRequest;

/**
 * List Bigtable instances in a project
 *
 * @param string $projectId The Google Cloud project ID
 */
function list_instance(string $projectId): void
{
    $instanceAdminClient = new BigtableInstanceAdminClient();

    $projectName = $instanceAdminClient->projectName($projectId);

    printf('Listing Instances:' . PHP_EOL);
    $listInstancesRequest = (new ListInstancesRequest())
        ->setParent($projectName);

    $getInstances = $instanceAdminClient->listInstances($listInstancesRequest)->getInstances();
    $instances = $getInstances->getIterator();

    foreach ($instances as $instance) {
        print($instance->getName() . PHP_EOL);
    }
}

Python

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import google.api_core.exceptions
from google.cloud import bigtable_admin_v2


def list_instances(project_id: str) -> None:
    """Lists Bigtable instances in a Google Cloud project.

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id').
    """
    client = bigtable_admin_v2.BigtableInstanceAdminClient()
    parent = f"projects/{project_id}"

    try:
        response = client.list_instances(parent=parent)
        for instance in response.instances:
            print(f"Instance name: {instance.name}")
            print(f"Display name: {instance.display_name}")
            print(f"State: {instance.state}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"API call failed: {e}")

Ruby

במאמר ספריות הלקוח של Bigtable מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

bigtable.instances.all do |instance|
  puts "Instance: #{instance.instance_id}"
end

המאמרים הבאים

כדי לחפש ולסנן דוגמאות קוד למוצרים אחרים של Google Cloud , ראו דפדפן לדוגמה שלGoogle Cloud .