Início rápido

Uso básico da biblioteca de cliente do Diretório de serviços.

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

Go

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

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


// Sample quickstart is a program that uses Cloud Service Directory
// create. delete, and resolve functionality.
package main

import (
	"context"
	"fmt"
	"log"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "cloud.google.com/go/servicedirectory/apiv1/servicedirectorypb"
)

func main() {
	projectID := "your-project-id"
	location := "us-west1"
	serviceID := "golang-quickstart-service"
	namespaceID := "golang-quickstart-namespace"
	endpointID := "golang-quickstart-endpoint"

	ctx := context.Background()
	// Create a registration client.
	registry, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		log.Fatalf("servicedirectory.NewRegistrationClient: %v", err)
	}
	defer registry.Close()

	// Create a lookup client.
	resolver, err := servicedirectory.NewLookupClient(ctx)
	if err != nil {
		log.Fatalf("servicedirectory.NewLookupClient: %v", err)
	}
	defer resolver.Close()

	// Create a Namespace.
	createNsReq := &sdpb.CreateNamespaceRequest{
		Parent:      fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		NamespaceId: namespaceID,
	}
	namespace, err := registry.CreateNamespace(ctx, createNsReq)
	if err != nil {
		log.Fatalf("servicedirectory.CreateNamespace: %v", err)
	}

	// Create a Service.
	createServiceReq := &sdpb.CreateServiceRequest{
		Parent:    namespace.Name,
		ServiceId: serviceID,
		Service: &sdpb.Service{
			Annotations: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
		},
	}
	service, err := registry.CreateService(ctx, createServiceReq)
	if err != nil {
		log.Fatalf("servicedirectory.CreateService: %v", err)
	}

	// Create an Endpoint.
	createEndpointReq := &sdpb.CreateEndpointRequest{
		Parent:     service.Name,
		EndpointId: endpointID,
		Endpoint: &sdpb.Endpoint{
			Address: "8.8.8.8",
			Port:    8080,
			Annotations: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
		},
	}
	_, err = registry.CreateEndpoint(ctx, createEndpointReq)
	if err != nil {
		log.Fatalf("servicedirectory.CreateEndpoint: %v", err)
	}

	// Now Resolve the service.
	lookupRequest := &sdpb.ResolveServiceRequest{
		Name: service.Name,
	}
	result, err := resolver.ResolveService(ctx, lookupRequest)
	if err != nil {
		log.Fatalf("servicedirectory.ResolveService: %v", err)
		return
	}

	fmt.Printf("Successfully Resolved Service %v", result)

	// Delete the namespace.
	deleteNsReq := &sdpb.DeleteNamespaceRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/namespaces/%s",
			projectID, location, namespaceID),
	}
	registry.DeleteNamespace(ctx, deleteNsReq) // Ignore results.
}

Java

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

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


import com.google.cloud.servicedirectory.v1.LocationName;
import com.google.cloud.servicedirectory.v1.Namespace;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient.ListNamespacesPagedResponse;
import java.io.IOException;

public class Quickstart {

  public static void quickstart() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "your-region";
    quickstart(projectId, locationId);
  }

  public static void quickstart(String projectId, String locationId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (RegistrationServiceClient client = RegistrationServiceClient.create()) {

      // The project and location that hold the namespace to list.
      LocationName parent = LocationName.of(projectId, locationId);

      // Call the API.
      ListNamespacesPagedResponse response = client.listNamespaces(parent);

      // Iterate over each namespace and print its name.
      System.out.println("Namespaces:");
      for (Namespace namespace : response.iterateAll()) {
        System.out.println(namespace.getName());
      }
    }
  }
}

Node.js

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

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

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-central1';

// Imports the Google Cloud client library
const {
  RegistrationServiceClient,
} = require('@google-cloud/service-directory');

// Creates a client
const registrationServiceClient = new RegistrationServiceClient();

// Build the location name
const locationName = registrationServiceClient.locationPath(
  projectId,
  locationId
);

async function listNamespaces() {
  const [namespaces] = await registrationServiceClient.listNamespaces({
    parent: locationName,
  });

  console.log('Namespaces: ');
  for (const n of namespaces) {
    console.log(`${n.name}`);
  }
  return namespaces;
}

return listNamespaces();

PHP

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

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

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;

/** Uncomment and populate these variables in your code */
// $projectId = '[YOUR_PROJECT_ID]';
// $locationId = '[YOUR_GCP_REGION]';

// Instantiate a client.
$client = new RegistrationServiceClient();

// Run request.
$locationName = RegistrationServiceClient::locationName($projectId, $locationId);
$pagedResponse = $client->listNamespaces($locationName);

// Iterate over each namespace and print its name.
print('Namespaces: ' . PHP_EOL);
foreach ($pagedResponse->iterateAllElements() as $namespace) {
    print($namespace->getName() . PHP_EOL);
}

Python

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

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

from google.cloud import servicedirectory_v1
from google.cloud.servicedirectory_v1.services.registration_service.pagers import (
    ListNamespacesPager,
)


def list_namespaces(project_id: str, location: str) -> ListNamespacesPager:
    """Lists all namespaces in the given location.

    Args:
        project_id: The Google Cloud project id.
        location: The location which contains the namespaces to list.

    Returns:
        All namespaces in the given location.
    """

    client = servicedirectory_v1.RegistrationServiceClient()

    response = client.list_namespaces(
        parent=f"projects/{project_id}/locations/{location}"
    )

    print(f"Listed namespaces in {location}.")
    for namespace in response:
        print(f"Namespace: {namespace.name}")

    return response

Ruby

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

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

# Imports the Google Cloud client library
require "google/cloud/service_directory"

# Your Google Cloud Platform project ID
project = ENV["GOOGLE_CLOUD_PROJECT"]

# Location of the Service Directory Namespace
location = "us-central1"

# Initialize a client
registration_service = Google::Cloud::ServiceDirectory.registration_service

# The resource name of the project
location_name = registration_service.location_path(
  project: project, location: location
)

# Request list of namespaces in the project
response = registration_service.list_namespaces parent: location_name

# List all namespaces for your project
puts "Namespaces: "
response.each do |namespace|
  puts namespace.name
end

A seguir

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