서비스 디렉터리 구성

이 페이지에서는 서비스 디렉터리 네임스페이스를 설정하고, 네임스페이스에 서비스를 추가하고, 서비스에 엔드포인트를 추가하는 방법을 설명합니다. 이 페이지에서 명령어를 실행하기 전에 서비스 디렉터리 개요 및 서비스 디렉터리와 관련된 주요 용어의 개념을 숙지해야 합니다.

프로젝트 설정

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. Service Directory API 사용 설정

    API 사용 설정

  5. Google Cloud CLI를 설치합니다.
  6. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  7. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  8. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  9. Service Directory API 사용 설정

    API 사용 설정

  10. Google Cloud CLI를 설치합니다.
  11. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init

서비스 디렉터리 리소스 구성

네임스페이스 구성

선택한 리전의 프로젝트 네임스페이스를 만듭니다. 이 리전에서 모든 서비스 및 엔드포인트가 실행되는 위치에 있지 않아도 되지만, 가능하면 닫아야 합니다. 모든 서비스 디렉터리 리전에 서비스를 등록할 수 있습니다. 여전히 견고성이 없습니다. 프로젝트는 한 리전 내에 여러 개의 네임스페이스를 포함할 수 있으며 여러 리전에는 네임스페이스가 있을 수 있습니다. 단일 네임스페이스는 여러 리전에 걸쳐 있을 수 없습니다.

콘솔

  1. Google Cloud Console에서 서비스 디렉터리 네임스페이스 페이지로 이동합니다.
    서비스 디렉터리 네임스페이스 페이지로 이동
  2. 네임스페이스 만들기를 클릭합니다.
  3. 리전 풀다운 메뉴에서 네임스페이스의 리전을 선택합니다.
  4. 네임스페이스 이름 필드에 네임스페이스 이름을 지정합니다.
  5. 만들기를 클릭합니다.

gcloud

명령줄에서 서비스 디렉터리를 사용하려면 먼저 Cloud SDK를 최신 버전으로 설치하거나 업그레이드하세요.

  1. 네임스페이스 만들기

    gcloud service-directory namespaces create NAMESPACE \
       --location REGION
    

    다음을 바꿉니다.

    • NAMESPACE: 만들려는 네임스페이스의 이름입니다.
    • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.
  2. (선택사항): 네임스페이스에 IAM 정책을 설정합니다. 이렇게 하면 지정된 사용자 또는 그룹에 이 네임스페이스 및 네임스페이스에 속하는 모든 서비스에 지정된 역할이 부여됩니다.

    gcloud service-directory namespaces add-iam-policy-binding NAMESPACE \
    --member user:someone@example.com \
    --role ROLE \
    --location REGION
    

    다음을 바꿉니다.

    • NAMESPACE: 만든 네임스페이스의 이름입니다.
    • ROLE: 부여하는 역할입니다.
    • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 서비스 디렉터리 C# SDK를 설치합니다.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.ServiceDirectory.V1;

public class CreateNamespaceSample
{
    public Namespace CreateNamespace(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace")
    {
        // Create client
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        // Initialize request argument(s)
        var locationName = LocationName.FromProjectLocation(projectId, locationId);
        return registrationServiceClient.CreateNamespace(locationName, new Namespace(), namespaceId);
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 서비스 디렉터리 Go SDK를 설치합니다.

import (
	"context"
	"fmt"
	"io"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func createNamespace(w io.Writer, projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"

	ctx := context.Background()
	// Create a registration client.
	client, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewRegistrationClient: %v", err)
	}

	defer client.Close()
	// Create a Namespace.
	req := &sdpb.CreateNamespaceRequest{
		Parent:      fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		NamespaceId: namespaceID,
	}
	resp, err := client.CreateNamespace(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateNamespace: %v", err)
	}
	fmt.Fprintf(w, "servicedirectory.CreateNamespace result: %s\n", resp.Name)
	return nil
}

자바

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 서비스 디렉터리 자바 SDK를 설치합니다.


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

public class NamespacesCreate {

  public static void createNamespace() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "your-region";
    // This is user-created; must be unique within the project/region above.
    String namespaceId = "your-namespace";
    createNamespace(projectId, locationId, namespaceId);
  }

  // Create a new namespace.
  public static void createNamespace(String projectId, String locationId, String namespaceId)
      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 to create the namespace in.
      LocationName parent = LocationName.of(projectId, locationId);

      // The namespace object to create. Here, we use the default instance.
      Namespace namespace = Namespace.newBuilder().build();

      // Send the request to create the namespace.
      Namespace createdNamespace = client.createNamespace(parent, namespace, namespaceId);

      // Process the response.
      System.out.println("Created Namespace: " + createdNamespace.getName());
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 서비스 디렉터리 Node.js SDK를 설치합니다.

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

// 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 createNamespace() {
  const [namespace] = await registrationServiceClient.createNamespace({
    parent: locationName,
    namespaceId: namespaceId,
  });

  console.log(`Created namespace: ${namespace.name}`);
  return namespace;
}

return createNamespace();

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 서비스 디렉터리 PHP SDK를 설치합니다.

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;
use Google\Cloud\ServiceDirectory\V1beta1\PBNamespace;

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

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

// Run request.
$locationName = RegistrationServiceClient::locationName($projectId, $locationId);
$namespace = $client->createNamespace($locationName, $namespaceId, new PBNamespace());

// Print results.
printf('Created Namespace: %s' . PHP_EOL, $namespace->getName());

Python

이 코드를 실행하려면 먼저 Python 개발 환경을 설정하고 서비스 디렉터리 Python SDK를 설치합니다.

def create_namespace(project_id, location_id, namespace_id):
    """Creates a namespace in the given location."""

    client = servicedirectory_v1.RegistrationServiceClient()

    namespace = servicedirectory_v1.Namespace(
        name=client.namespace_path(project_id, location_id, namespace_id))

    response = client.create_namespace(
        parent=f'projects/{project_id}/locations/{location_id}',
        namespace=namespace,
        namespace_id=namespace_id,
    )

    print(f'Created namespace {response.name}.')

    return response

Ruby

이 코드를 실행하려면 먼저 Ruby 개발 환경을 설정하고 서비스 디렉터리 Ruby SDK를 설치합니다.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the new namespace"
# namespace = "The name of the namespace you are creating"

require "google/cloud/service_directory"

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

# The parent path of the namespace
parent = registration_service.location_path(
  project: project, location: location
)

# Use the Service Directory API to create the namespace
response = registration_service.create_namespace(
  parent: parent, namespace_id: namespace
)
puts "Created namespace: #{response.name}"

서비스 구성

네임스페이스에서 서비스를 만듭니다. 서비스는 이름과 선택사항 서비스 관련 메타데이터로 구성됩니다. 서비스 이름의 형식에 몇 가지 제한사항이 있습니다.

  • 서비스 이름은 네임스페이스 내에서 고유해야 합니다.
  • 서비스 이름은 DNS 라벨의 이름 지정 규칙을 따라야 합니다.

콘솔

  1. Google Cloud Console에서 서비스 디렉터리 네임스페이스 페이지로 이동합니다.
    서비스 디렉터리 네임스페이스 페이지로 이동
  2. 네임스페이스를 클릭합니다.
  3. 서비스 추가를 클릭합니다.
  4. 서비스 이름을 입력합니다.
  5. 선택사항 서비스에 메타데이터를 추가하려면 다음을 수행합니다.
    1. 서비스 메타데이터를 클릭합니다.
    2. 메타데이터 추가를 클릭합니다.
    3. 을 추가합니다.
    4. 메타데이터 쌍을 더 추가하려면 메타데이터 추가를 다시 클릭합니다.
  6. 만들기를 클릭합니다.

gcloud

명령줄에서 서비스 디렉터리를 사용하려면 먼저 Cloud SDK를 최신 버전으로 설치하거나 업그레이드하세요.

  1. 네임스페이스에서 서비스를 만듭니다.

    gcloud service-directory services create SERVICE \
       --metadata KEY_1=VALUE_1,KEY_2=VALUE_2 \
       --namespace NAMESPACE \
       --location REGION
    

    다음을 바꿉니다.

    • SERVICE: 만들려는 서비스의 이름입니다.
    • NAMESPACE: 서비스가 포함된 네임스페이스에 제공한 이름입니다.
    • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.
    • KEY_1,VALUE_1,KEY_2, VALUE_2: 쌍으로 설정된 키 및 값 문자열입니다.
  2. (선택사항): 서비스에 IAM 정책을 설정합니다. 그러면 지정한 사용자 또는 그룹에 이 서비스와 서비스에 속한 모든 엔드포인트가 지정된 역할이 부여됩니다.

    gcloud service-directory services add-iam-policy-binding SERVICE \
    --member user:someone@example.com \
    --role ROLE \
    --namespace NAMESPACE \
    --location REGION
    

    다음을 바꿉니다.

    • SERVICE: 서비스에 제공한 이름입니다.
    • NAMESPACE: 만든 네임스페이스의 이름입니다.
    • ROLE: 부여하는 역할입니다.
    • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 서비스 디렉터리 C# SDK를 설치합니다.


using Google.Cloud.ServiceDirectory.V1;

public class CreateServiceSample
{
    public Service CreateService(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId = "test-service")
    {
        // Create client
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        // Initialize request argument(s)
        var namespaceName = NamespaceName.FromProjectLocationNamespace(projectId, locationId, namespaceId);
        return registrationServiceClient.CreateService(namespaceName, new Service(), serviceId);
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 서비스 디렉터리 Go SDK를 설치합니다.

import (
	"context"
	"fmt"
	"io"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func createService(w io.Writer, projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"
	serviceID := "golang-test-service"

	ctx := context.Background()
	// Create a registration client.
	client, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewRegistrationClient: %v", err)
	}

	defer client.Close()
	// Create a Service.
	req := &sdpb.CreateServiceRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s/namespaces/%s", projectID, location, namespaceID),
		ServiceId: serviceID,
		Service: &sdpb.Service{
			Annotations: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
		},
	}
	service, err := client.CreateService(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateSerice: %v", err)
	}
	fmt.Fprintf(w, "servicedirectory.Createservice result %s\n", service.Name)
	return nil
}

자바

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 서비스 디렉터리 자바 SDK를 설치합니다.


import com.google.cloud.servicedirectory.v1.NamespaceName;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import com.google.cloud.servicedirectory.v1.Service;
import java.io.IOException;

public class ServicesCreate {

  public static void createService() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // These variables should refer to an existing Service Directory namespace.
    String projectId = "your-project-id";
    String locationId = "your-region";
    String namespaceId = "your-namespace";
    // This is user-created; must be unique within the namespace above.
    String serviceId = "your-service";
    createService(projectId, locationId, namespaceId, serviceId);
  }

  // Create a new service.
  public static void createService(
      String projectId, String locationId, String namespaceId, String serviceId)
      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 namespace to create the service in.
      NamespaceName parent = NamespaceName.of(projectId, locationId, namespaceId);

      // The service object to create.
      // Optionally add some annotations for the service.
      Service service = Service.newBuilder().putAnnotations("protocol", "tcp").build();

      // Send the request to create the namespace.
      Service createdService = client.createService(parent, service, serviceId);

      // Process the response.
      System.out.println("Created Service: " + createdService.getName());
      System.out.println("Annotations: " + createdService.getAnnotations());
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 서비스 디렉터리 Node.js SDK를 설치합니다.

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

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

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

// Build the namespace name
const namespaceName = registrationServiceClient.namespacePath(
  projectId,
  locationId,
  namespaceId
);

async function createService() {
  const [service] = await registrationServiceClient.createService({
    parent: namespaceName,
    serviceId: serviceId,
  });

  console.log(`Created service: ${service.name}`);
  return service;
}

return createService();

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 서비스 디렉터리 PHP SDK를 설치합니다.

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;
use Google\Cloud\ServiceDirectory\V1beta1\Service;

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

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

// Run request.
$namespaceName = RegistrationServiceClient::namespaceName($projectId, $locationId, $namespaceId);
$service = $client->createService($namespaceName, $serviceId, new Service());

// Print results.
printf('Created Service: %s' . PHP_EOL, $service->getName());

Python

이 코드를 실행하려면 먼저 Python 개발 환경을 설정하고 서비스 디렉터리 Python SDK를 설치합니다.

def create_service(project_id, location_id, namespace_id, service_id):
    """Creates a service in the given namespace."""

    client = servicedirectory_v1.RegistrationServiceClient()

    service = servicedirectory_v1.Service(
        name=client.service_path(project_id, location_id, namespace_id,
                                 service_id))

    response = client.create_service(
        parent=client.namespace_path(project_id, location_id, namespace_id),
        service=service,
        service_id=service_id,
    )

    print(f'Created service {response.name}.')

    return response

Ruby

이 코드를 실행하려면 먼저 Ruby 개발 환경을 설정하고 서비스 디렉터리 Ruby SDK를 설치합니다.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the namespace"
# namespace = "The name of the parent namespace"
# service   = "The name of the service you are creating"

require "google/cloud/service_directory"

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

# The parent path of the service
parent = registration_service.namespace_path(
  project: project, location: location, namespace: namespace
)

# Use the Service Directory API to create the service
response = registration_service.create_service parent: parent, service_id: service
puts "Created service: #{response.name}"

엔드포인트 구성

서비스가 등록되었으면 엔드포인트를 추가합니다. 엔드포인트는 고유한 이름과 주소, 포트, 키/값 메타데이터의 선택적 필드로 구성됩니다. 지정된 경우 유효한 IPv4 또는 IPv6 주소여야 합니다.

콘솔

  1. Google Cloud Console에서 서비스 디렉터리 네임스페이스 페이지로 이동합니다.
    서비스 디렉터리 네임스페이스 페이지로 이동
  2. 네임스페이스를 클릭합니다.
  3. 서비스를 클릭합니다.
  4. 엔드포인트 추가를 클릭합니다.
  5. 엔드포인트 이름을 입력합니다.
  6. IPv4 또는 IPv6 IP 주소를 입력합니다.
  7. 포트 번호를 입력합니다.
  8. 선택사항 엔드포인트에 메타데이터를 추가하려면 다음을 수행합니다.
    1. 엔드포인트 메타데이터를 클릭합니다.
    2. 메타데이터 추가를 클릭합니다.
    3. 을 추가합니다.
    4. 메타데이터 쌍을 더 추가하려면 메타데이터 추가를 다시 클릭합니다.
  9. 만들기를 클릭합니다.

gcloud

명령줄에서 서비스 디렉터리를 사용하려면 먼저 Cloud SDK를 최신 버전으로 설치하거나 업그레이드하세요.

서비스가 등록되었으면 엔드포인트를 추가합니다.

gcloud service-directory endpoints create ENDPOINT \
   --address IP_ADDRESS \
   --port PORT_NUMBER \
   --metadata KEY_1=VALUE_1,KEY_2=VALUE_2 \
   --service SERVICE \
   --namespace NAMESPACE \
   --location REGION
gcloud service-directory endpoints create ENDPOINT2 \
   --address IP_ADDRESS2 \
   --port PORT_NUMBER2 \
   --service SERVICE \
   --namespace NAMESPACE \
   --location REGION

다음 값을 바꿉니다.

  • ENDPOINTENDPOINT2: 서비스에서 만드는 엔드포인트의 이름입니다.
  • IP_ADDRESSIP_ADDRESS2: 각각 엔드포인트의 IPv6 및 IPv4 주소입니다.
  • PORT_NUMBERPORT_NUMBER2: 엔드포인트가 실행되는 포트입니다.
  • SERVICE: 만들려는 서비스의 이름입니다.
  • NAMESPACE: 서비스가 포함된 네임스페이스에 제공한 이름입니다.
  • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.
  • KEY_1,VALUE_1,KEY_2, VALUE_2: 쌍으로 설정된 키 및 값 문자열입니다.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 서비스 디렉터리 C# SDK를 설치합니다.


using Google.Cloud.ServiceDirectory.V1;

public class CreateEndpointSample
{
	public Endpoint CreateEndpoint(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId = "test-service",
        string endpointId = "test-endpoint")
    {
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        var serviceName = ServiceName.FromProjectLocationNamespaceService(projectId, locationId, namespaceId, serviceId);
        return registrationServiceClient.CreateEndpoint(serviceName, new Endpoint(), endpointId);
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 서비스 디렉터리 Go SDK를 설치합니다.

import (
	"context"
	"fmt"
	"io"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func createEndpoint(w io.Writer, projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"
	serviceID := "golang-test-service"
	endpointID := "golang-test-endpoint"

	ctx := context.Background()
	// Create a registration client.
	client, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewRegistrationClient: %v", err)
	}

	defer client.Close()
	// Create an Endpoint.
	req := &sdpb.CreateEndpointRequest{
		Parent:     fmt.Sprintf("projects/%s/locations/%s/namespaces/%s/services/%s", projectID, location, namespaceID, serviceID),
		EndpointId: endpointID,
		Endpoint: &sdpb.Endpoint{
			Address: "8.8.8.8",
			Port:    8080,
			Annotations: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
		},
	}
	endpoint, err := client.CreateEndpoint(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateEndpoint: %v", err)
	}
	fmt.Fprintf(w, "servicedirectory.CreateEndpoint result: %s", endpoint.Name)
	return nil
}

자바

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 서비스 디렉터리 자바 SDK를 설치합니다.


import com.google.cloud.servicedirectory.v1.Endpoint;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import com.google.cloud.servicedirectory.v1.ServiceName;
import java.io.IOException;

public class EndpointsCreate {

  public static void createEndpoint() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // These variables should refer to an existing Service Directory service.
    String projectId = "your-project-id";
    String locationId = "your-region";
    String namespaceId = "your-namespace";
    String serviceId = "your-service";
    // This is user-created; must be unique within the service above.
    String endpointId = "your-endpoint";
    createEndpoint(projectId, locationId, namespaceId, serviceId, endpointId);
  }

  // Create a new endpoint.
  public static void createEndpoint(
      String projectId, String locationId, String namespaceId, String serviceId, String endpointId)
      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 service to create the endpoint in.
      ServiceName parent = ServiceName.of(projectId, locationId, namespaceId, serviceId);

      // The endpoint to create, with fields filled in.
      // Optionally set an IP address and port for the endpoint.
      Endpoint endpoint = Endpoint.newBuilder().setAddress("10.0.0.1").setPort(443).build();

      // Send the request to create the endpoint.
      Endpoint createdEndpoint = client.createEndpoint(parent, endpoint, endpointId);

      // Process the response.
      System.out.println("Created Endpoint: " + createdEndpoint.getName());
      System.out.println("IP Address: " + createdEndpoint.getAddress());
      System.out.println("Port: " + createdEndpoint.getPort());
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 서비스 디렉터리 Node.js SDK를 설치합니다.

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

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

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

// Build the service name
const serviceName = registrationServiceClient.servicePath(
  projectId,
  locationId,
  namespaceId,
  serviceId
);

async function createEndpoint() {
  const [endpoint] = await registrationServiceClient.createEndpoint({
    parent: serviceName,
    endpointId: endpointId,
    endpoint: {address: '10.0.0.1', port: 8080},
  });

  console.log(`Created endpoint: ${endpoint.name}`);
  return endpoint;
}

return createEndpoint();

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 서비스 디렉터리 PHP SDK를 설치합니다.

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;
use Google\Cloud\ServiceDirectory\V1beta1\Endpoint;

/** Uncomment and populate these variables in your code */
// $projectId = '[YOUR_PROJECT_ID]';
// $locationId = '[YOUR_GCP_REGION]';
// $namespaceId = '[YOUR_NAMESPACE_NAME]';
// $serviceId = '[YOUR_SERVICE_NAME]';
// $endpointId = '[YOUR_ENDPOINT_NAME]';
// $ip = '[IP_ADDRESS]';  // (Optional) Defaults to ''
// $port = [PORT];  // (Optional) Defaults to 0

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

// Construct Endpoint object.
$endpointObject = (new Endpoint())
    ->setAddress($ip)
    ->setPort($port);

// Run request.
$serviceName = RegistrationServiceClient::serviceName($projectId, $locationId, $namespaceId, $serviceId);
$endpoint = $client->createEndpoint($serviceName, $endpointId, $endpointObject);

// Print results.
printf('Created Endpoint: %s' . PHP_EOL, $endpoint->getName());
printf('  IP: %s' . PHP_EOL, $endpoint->getAddress());
printf('  Port: %d' . PHP_EOL, $endpoint->getPort());

Python

이 코드를 실행하려면 먼저 Python 개발 환경을 설정하고 서비스 디렉터리 Python SDK를 설치합니다.

def create_endpoint(project_id, location_id, namespace_id, service_id,
                    endpoint_id, address, port):
    """Creates a endpoint in the given service."""

    client = servicedirectory_v1.RegistrationServiceClient()

    endpoint = servicedirectory_v1.Endpoint(
        name=client.endpoint_path(project_id, location_id, namespace_id,
                                  service_id, endpoint_id),
        address=address,
        port=port)

    response = client.create_endpoint(
        parent=client.service_path(project_id, location_id, namespace_id,
                                   service_id),
        endpoint=endpoint,
        endpoint_id=endpoint_id,
    )

    print(f'Created endpoint {response.name}.')

    return response

Ruby

이 코드를 실행하려면 먼저 Ruby 개발 환경을 설정하고 서비스 디렉터리 Ruby SDK를 설치합니다.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the namespace"
# namespace = "The name of the parent namespace"
# service   = "The name of the parent service"
# endpoint  = "The name of the endpoint you are creating"

require "google/cloud/service_directory"

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

# The parent path of the endpoint
parent = registration_service.service_path(
  project:   project,
  location:  location,
  namespace: namespace,
  service:   service
)

# Set the IP Address and Port on the Endpoint
endpoint_data = Google::Cloud::ServiceDirectory::V1::Endpoint.new(
  address: "10.0.0.1",
  port:    443
)

# Use the Service Directory API to create the endpoint
response = registration_service.create_endpoint(
  parent: parent, endpoint_id: endpoint, endpoint: endpoint_data
)
puts "Created endpoint: #{response.name}"

서비스 해결

서비스 디렉터리를 사용하면 클라이언트가 DNS, HTTP, gRPC를 사용하여 서비스를 확인할 수 있습니다. 서비스를 확인하면 서비스의 모든 속성과 모든 엔드포인트와 메타데이터가 반환됩니다.

gcloud

명령줄에서 서비스 디렉터리를 사용하려면 먼저 Cloud SDK를 최신 버전으로 설치하거나 업그레이드하세요.

gcloud service-directory services resolve SERVICE \
   --namespace NAMESPACE \
   --location REGION

다음을 바꿉니다.

  • SERVICE: 만들려는 서비스의 이름입니다.
  • NAMESPACE: 서비스를 포함하는 네임스페이스에 제공한 이름입니다.
  • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 서비스 디렉터리 C# SDK를 설치합니다.


using Google.Cloud.ServiceDirectory.V1;

public class ResolveServiceSample
{
    public Service ResolveService(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId = "test-service")
    {
        // Create client
        LookupServiceClient lookupServiceClient = LookupServiceClient.Create();
        // Initialize request argument(s)
        ResolveServiceRequest request = new ResolveServiceRequest
        {
            ServiceName = ServiceName.FromProjectLocationNamespaceService(projectId, locationId, namespaceId, serviceId),
        };
        // Make the request
        ResolveServiceResponse response = lookupServiceClient.ResolveService(request);
        return response.Service;
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 서비스 디렉터리 Go SDK를 설치합니다.

import (
	"context"
	"fmt"
	"io"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func resolveService(w io.Writer, projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"
	serviceID := "golang-test-service"

	ctx := context.Background()
	// Create a lookup client.
	resolver, err := servicedirectory.NewLookupClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewLookupClient: %v", err)
	}

	defer resolver.Close()
	// Now Resolve the service.
	req := &sdpb.ResolveServiceRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/namespaces/%s/services/%s", projectID, location, namespaceID, serviceID),
	}
	result, err := resolver.ResolveService(ctx, req)
	if err != nil {
		return fmt.Errorf("ResolveService: %v", err)
	}

	fmt.Fprintf(w, "Successfully Resolved Service %v\n", result)
	return nil
}

자바

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 서비스 디렉터리 자바 SDK를 설치합니다.


import com.google.cloud.servicedirectory.v1.Endpoint;
import com.google.cloud.servicedirectory.v1.LookupServiceClient;
import com.google.cloud.servicedirectory.v1.ResolveServiceRequest;
import com.google.cloud.servicedirectory.v1.ResolveServiceResponse;
import com.google.cloud.servicedirectory.v1.ServiceName;
import java.io.IOException;

public class ServicesResolve {

  public static void resolveService() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // These variables should refer to an existing Service Directory service.
    String projectId = "your-project-id";
    String locationId = "your-region";
    String namespaceId = "your-namespace";
    String serviceId = "your-service";
    resolveService(projectId, locationId, namespaceId, serviceId);
  }

  // Resolve a service.
  public static void resolveService(
      String projectId, String locationId, String namespaceId, String serviceId)
      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 (LookupServiceClient client = LookupServiceClient.create()) {
      // The service to resolve.
      ServiceName name = ServiceName.of(projectId, locationId, namespaceId, serviceId);

      // Construct the resolve request to be sent to the client.
      ResolveServiceRequest request =
          ResolveServiceRequest.newBuilder().setName(name.toString()).build();

      // Send the request to resolve the service.
      ResolveServiceResponse resolveResponse = client.resolveService(request);

      // Process the response.
      System.out.println("Resolved Service: " + resolveResponse.getService().getName());

      System.out.println("Endpoints found:");
      for (Endpoint endpoint : resolveResponse.getService().getEndpointsList()) {
        System.out.println(
            endpoint.getName() + " -- " + endpoint.getAddress() + ":" + endpoint.getPort());
      }
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 서비스 디렉터리 Node.js SDK를 설치합니다.

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

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

// Creates a client
const lookupServiceClient = new LookupServiceClient();

// Build the service name
const serviceName = lookupServiceClient.servicePath(
  projectId,
  locationId,
  namespaceId,
  serviceId
);

async function resolveService() {
  const [response] = await lookupServiceClient.resolveService({
    name: serviceName,
  });

  console.log(`Resolved service: ${response.service.name}`);
  for (const e of response.service.endpoints) {
    console.log(`\n${e.name}`);
    console.log(`Address: ${e.address}`);
    console.log(`Port: ${e.port}\n`);
  }
  return response.service;
}

return resolveService();

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 서비스 디렉터리 PHP SDK를 설치합니다.

use Google\Cloud\ServiceDirectory\V1beta1\LookupServiceClient;
use Google\Cloud\ServiceDirectory\V1beta1\Service;

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

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

// Run request.
$serviceName = LookupServiceClient::serviceName($projectId, $locationId, $namespaceId, $serviceId);
$service = $client->resolveService($serviceName)->getService();

// Print results.
printf('Resolved Service: %s' . PHP_EOL, $service->getName());
print('Endpoints:' . PHP_EOL);
foreach ($service->getEndpoints() as $endpoint) {
    printf('  Name: %s' . PHP_EOL, $endpoint->getName());
    printf('    IP: %s' . PHP_EOL, $endpoint->getAddress());
    printf('    Port: %d' . PHP_EOL, $endpoint->getPort());
}

Python

이 코드를 실행하려면 먼저 Python 개발 환경을 설정하고 서비스 디렉터리 Python SDK를 설치합니다.

def resolve_service(project_id, location_id, namespace_id, service_id):
    """Resolves a service in the given namespace."""

    client = servicedirectory_v1.LookupServiceClient()

    request = servicedirectory_v1.ResolveServiceRequest(
        name=servicedirectory_v1.RegistrationServiceClient().service_path(
            project_id, location_id, namespace_id, service_id))

    response = client.resolve_service(request=request)

    print('Endpoints found:')
    for endpoint in response.service.endpoints:
        print(f'{endpoint.name} -- {endpoint.address}:{endpoint.port}')

    return response

Ruby

이 코드를 실행하려면 먼저 Ruby 개발 환경을 설정하고 서비스 디렉터리 Ruby SDK를 설치합니다.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the namespace"
# namespace = "The name of the parent namespace"
# service   = "The name of the service"

require "google/cloud/service_directory"

# Initialize the client
lookup_service = Google::Cloud::ServiceDirectory.lookup_service

# The name of the service
service_path = lookup_service.service_path(
  project:   project,
  location:  location,
  namespace: namespace,
  service:   service
)

# Use the Service Directory API to resolve the service
response = lookup_service.resolve_service name: service_path
puts "Resolved service: #{response.service.name}"
puts "Endpoints: "
response.service.endpoints.each do |endpoint|
  puts "#{endpoint.name} #{endpoint.address} #{endpoint.port}"
end

리소스 삭제

서비스에서 엔드포인트 삭제

콘솔

  1. Google Cloud Console에서 서비스 디렉터리 네임스페이스 페이지로 이동합니다.
    서비스 디렉터리 네임스페이스 페이지로 이동
  2. 엔드포인트를 삭제할 네임스페이스를 클릭합니다.
  3. 엔드포인트를 삭제할 서비스를 클릭합니다.
  4. 삭제할 엔드포인트 옆의 체크박스를 클릭합니다.
  5. 삭제를 클릭합니다.
  6. 확인 대화상자에서 삭제를 다시 클릭합니다 .

gcloud

명령줄에서 서비스 디렉터리를 사용하려면 먼저 Cloud SDK를 최신 버전으로 설치하거나 업그레이드하세요.

gcloud service-directory endpoints delete ENDPOINT \
    --service=SERVICE \
    --namespace=NAMESPACE \
    --location=REGION

다음을 바꿉니다.

  • SERVICE: 만들려는 서비스의 이름입니다.
  • NAMESPACE: 서비스가 포함된 네임스페이스에 제공한 이름입니다.
  • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 서비스 디렉터리 C# SDK를 설치합니다.


using Google.Cloud.ServiceDirectory.V1;

public class DeleteEndpointSample
{
    public void DeleteEndpoint(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId = "test-service",
        string endpointId = "test-endpoint")
    {
        // Create client
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        // Initialize request argument(s)
        var endpointName = EndpointName.FromProjectLocationNamespaceServiceEndpoint(projectId, locationId, namespaceId, serviceId, endpointId);
        registrationServiceClient.DeleteEndpoint(endpointName);
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 서비스 디렉터리 Go SDK를 설치합니다.

import (
	"context"
	"fmt"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func deleteEndpoint(projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"
	serviceID := "golang-test-service"
	endpointID := "golang-test-endpoint"

	ctx := context.Background()
	// Create a registration client.
	client, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewRegistrationClient: %v", err)
	}

	defer client.Close()
	// Delete an Endpoint
	req := &sdpb.DeleteEndpointRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/namespaces/%s/services/%s/endpoints/%s", projectID, location, namespaceID, serviceID, endpointID),
	}
	if err := client.DeleteEndpoint(ctx, req); err != nil {
		return fmt.Errorf("DeleteEndpoint: %v", err)
	}
	return nil
}

자바

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 서비스 디렉터리 자바 SDK를 설치합니다.


import com.google.cloud.servicedirectory.v1.EndpointName;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import java.io.IOException;

public class EndpointsDelete {

  public static void deleteEndpoint() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // These variables should refer to an existing Service Directory endpoint.
    String projectId = "your-project-id";
    String locationId = "your-region";
    String namespaceId = "your-namespace";
    String serviceId = "your-service";
    String endpointId = "your-endpoint";
    deleteEndpoint(projectId, locationId, namespaceId, serviceId, endpointId);
  }

  // Delete an endpoint.
  public static void deleteEndpoint(
      String projectId, String locationId, String namespaceId, String serviceId, String endpointId)
      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 endpoint to delete.
      EndpointName endpointName =
          EndpointName.of(projectId, locationId, namespaceId, serviceId, endpointId);

      // Send the request to delete the endpoint.
      client.deleteEndpoint(endpointName);

      // Log the action.
      System.out.println("Deleted Endpoint: " + endpointName.toString());
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 서비스 디렉터리 Node.js SDK를 설치합니다.

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

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

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

// Build the endpoint name
const endpointName = registrationServiceClient.endpointPath(
  projectId,
  locationId,
  namespaceId,
  serviceId,
  endpointId
);

async function deleteEndpoint() {
  await registrationServiceClient.deleteEndpoint({
    name: endpointName,
  });

  console.log(`Deleted endpoint: ${endpointName}`);
}

deleteEndpoint();

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 서비스 디렉터리 PHP SDK를 설치합니다.

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;

/** Uncomment and populate these variables in your code */
// $projectId = '[YOUR_PROJECT_ID]';
// $locationId = '[YOUR_GCP_REGION]';
// $namespaceId = '[YOUR_NAMESPACE_NAME]';
// $serviceId = '[YOUR_SERVICE_NAME]';
// $endpointId = '[YOUR_ENDPOINT_NAME]';

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

// Run request.
$endpointName = RegistrationServiceClient::endpointName($projectId, $locationId, $namespaceId, $serviceId, $endpointId);
$endpoint = $client->deleteEndpoint($endpointName);

// Print results.
printf('Deleted Endpoint: %s' . PHP_EOL, $endpointName);

Python

이 코드를 실행하려면 먼저 Python 개발 환경을 설정하고 서비스 디렉터리 Python SDK를 설치합니다.

def delete_endpoint(project_id, location_id, namespace_id, service_id,
                    endpoint_id):
    """Deletes a endpoin in the given service."""

    client = servicedirectory_v1.RegistrationServiceClient()

    endpoint_name = client.endpoint_path(project_id, location_id, namespace_id,
                                         service_id, endpoint_id)

    client.delete_endpoint(name=endpoint_name)

    print(f'Deleted endpoint {endpoint_name}.')

Ruby

이 코드를 실행하려면 먼저 Ruby 개발 환경을 설정하고 서비스 디렉터리 Ruby SDK를 설치합니다.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the namespace"
# namespace = "The name of the parent namespace"
# service   = "The name of the parent service"
# endpoint  = "The name of the endpoint"

require "google/cloud/service_directory"

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

# The path of the endpoint
endpoint_path = registration_service.endpoint_path(
  project:   project,
  location:  location,
  namespace: namespace,
  service:   service,
  endpoint:  endpoint
)

# Use the Service Directory API to delete the endpoint
registration_service.delete_endpoint name: endpoint_path
puts "Deleted endpoint: #{endpoint_path}"

네임스페이스에서 서비스 삭제

엔드포인트가 있는 서비스를 삭제할 수 있습니다. 서비스가 삭제되면 모든 엔드포인트도 삭제됩니다.

서비스 디렉터리 영역이 가리키는 서비스를 삭제할 수 있습니다. 해당 서비스의 모든 DNS 쿼리는 NXDOMAIN을 반환합니다.

콘솔

  1. Google Cloud Console에서 서비스 디렉터리 네임스페이스 페이지로 이동합니다.
    서비스 디렉터리 네임스페이스 페이지로 이동
  2. 서비스를 삭제하려는 네임스페이스를 클릭합니다.
  3. 삭제하려는 서비스 옆의 체크박스를 클릭합니다.
  4. 삭제를 클릭합니다.
  5. 확인 대화상자에서 삭제를 다시 클릭합니다.

gcloud

명령줄에서 서비스 디렉터리를 사용하려면 먼저 Cloud SDK를 최신 버전으로 설치하거나 업그레이드하세요.

gcloud service-directory services delete SERVICE \
    --namespace=NAMESPACE \
    --location=REGION

다음을 바꿉니다.

  • SERVICE: 만들려는 서비스의 이름입니다.
  • NAMESPACE: 서비스가 포함된 네임스페이스에 제공한 이름입니다.
  • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 서비스 디렉터리 C# SDK를 설치합니다.


using Google.Cloud.ServiceDirectory.V1;

public class DeleteServiceSample
{
    public void DeleteService(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId = "test-service")
    {
        // Create client
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        // Initialize request argument(s)
        var serviceName = ServiceName.FromProjectLocationNamespaceService(projectId, locationId, namespaceId, serviceId);
        registrationServiceClient.DeleteService(serviceName);
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 서비스 디렉터리 Go SDK를 설치합니다.

import (
	"context"
	"fmt"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func deleteService(projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"
	serviceID := "golang-test-service"

	ctx := context.Background()
	// Create a registration client.
	client, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewRegistrationClient: %v", err)
	}

	defer client.Close()
	// Delete a service
	req := &sdpb.DeleteServiceRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/namespaces/%s/services/%s", projectID, location, namespaceID, serviceID),
	}
	if err := client.DeleteService(ctx, req); err != nil {
		return fmt.Errorf("DeleteService: %v", err)
	}
	return nil
}

자바

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 서비스 디렉터리 자바 SDK를 설치합니다.


import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import com.google.cloud.servicedirectory.v1.ServiceName;
import java.io.IOException;

public class ServicesDelete {

  public static void deleteService() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // These variables should refer to an existing Service Directory service.
    String projectId = "your-project-id";
    String locationId = "your-region";
    String namespaceId = "your-namespace";
    String serviceId = "your-service";
    deleteService(projectId, locationId, namespaceId, serviceId);
  }

  // Delete a service.
  public static void deleteService(
      String projectId, String locationId, String namespaceId, String serviceId)
      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 service to delete.
      ServiceName serviceName = ServiceName.of(projectId, locationId, namespaceId, serviceId);

      // Send the request to delete the service.
      client.deleteService(serviceName);

      // Log the action.
      System.out.println("Deleted Service: " + serviceName.toString());
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 서비스 디렉터리 Node.js SDK를 설치합니다.

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

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

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

// Build the service name
const serviceName = registrationServiceClient.servicePath(
  projectId,
  locationId,
  namespaceId,
  serviceId
);

async function deleteService() {
  await registrationServiceClient.deleteService({
    name: serviceName,
  });

  console.log(`Deleted service: ${serviceName}`);
}

deleteService();

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 서비스 디렉터리 PHP SDK를 설치합니다.

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;

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

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

// Run request.
$serviceName = RegistrationServiceClient::serviceName($projectId, $locationId, $namespaceId, $serviceId);
$client->deleteService($serviceName);

// Print results.
printf('Deleted Service: %s' . PHP_EOL, $serviceName);

Python

이 코드를 실행하려면 먼저 Python 개발 환경을 설정하고 서비스 디렉터리 Python SDK를 설치합니다.

def delete_service(project_id, location_id, namespace_id, service_id):
    """Deletes a service in the given namespace."""

    client = servicedirectory_v1.RegistrationServiceClient()

    service_name = client.service_path(project_id, location_id, namespace_id,
                                       service_id)

    client.delete_service(name=service_name)

    print(f'Deleted service {service_name}.')

Ruby

이 코드를 실행하려면 먼저 Ruby 개발 환경을 설정하고 서비스 디렉터리 Ruby SDK를 설치합니다.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the namespace"
# namespace = "The name of the parent namespace"
# service   = "The name of the service"

require "google/cloud/service_directory"

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

# The path of the service
service_path = registration_service.service_path(
  project:   project,
  location:  location,
  namespace: namespace,
  service:   service
)

# Use the Service Directory API to delete the service
registration_service.delete_service name: service_path
puts "Deleted service: #{service_path}"

네임스페이스 삭제

서비스 및 엔드포인트가 있는 네임스페이스를 삭제할 수 있습니다. 네임스페이스가 삭제되면 모든 서비스 및 엔드포인트도 삭제됩니다.

서비스 디렉터리 영역이 가리키는 네임스페이스를 삭제할 수 있습니다. 추가 DNS 쿼리 (영역 출처에 대한 SOA/NS 요청 제외)는 NXDOMAIN을 반환합니다.

콘솔

  1. Google Cloud Console에서 서비스 디렉터리 네임스페이스 페이지로 이동합니다.
    서비스 디렉터리 네임스페이스 페이지로 이동
  2. 삭제하려는 네임스페이스 옆의 체크박스를 클릭합니다.
  3. 삭제를 클릭합니다.
  4. 확인 대화상자에서 삭제를 다시 클릭합니다.

gcloud

명령줄에서 서비스 디렉터리를 사용하려면 먼저 Cloud SDK를 최신 버전으로 설치하거나 업그레이드하세요.

gcloud service-directory namespaces delete NAMESPACE \
    --location=REGION

다음을 바꿉니다.

  • NAMESPACE: 서비스가 포함된 네임스페이스에 제공한 이름입니다.
  • REGION: 네임스페이스가 포함된 Google Cloud 리전입니다.

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 서비스 디렉터리 C# SDK를 설치합니다.


using Google.Cloud.ServiceDirectory.V1;

public class DeleteNamespaceSample
{
    public void DeleteNamespace(
        string projectId = "projectId",
        string locationId = "us-east1",
        string namespaceId = "test-namespace")
    {
        // Create client
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        // Initialize request argument(s)
        var namespaceName = NamespaceName.FromProjectLocationNamespace(projectId, locationId, namespaceId);
        registrationServiceClient.DeleteNamespace(namespaceName);
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 서비스 디렉터리 Go SDK를 설치합니다.

import (
	"context"
	"fmt"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func deleteNamespace(projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"

	ctx := context.Background()
	// Create a registration client.
	client, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewRegistrationClient: %v", err)
	}

	defer client.Close()
	// Delete a Namespace.
	req := &sdpb.DeleteNamespaceRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/namespaces/%s", projectID, location, namespaceID),
	}
	if err := client.DeleteNamespace(ctx, req); err != nil {
		return fmt.Errorf("DeleteNamespace: %v", err)
	}
	return nil
}

자바

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 서비스 디렉터리 자바 SDK를 설치합니다.


import com.google.cloud.servicedirectory.v1.NamespaceName;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import java.io.IOException;

public class NamespacesDelete {

  public static void deleteNamespace() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // These variables should refer to an existing Service Directory namespace.
    String projectId = "your-project-id";
    String locationId = "your-region";
    String namespaceId = "your-namespace";
    deleteNamespace(projectId, locationId, namespaceId);
  }

  // Delete a namespace.
  public static void deleteNamespace(String projectId, String locationId, String namespaceId)
      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 namespace to delete.
      NamespaceName namespaceName = NamespaceName.of(projectId, locationId, namespaceId);

      // Send the request to delete the namespace.
      client.deleteNamespace(namespaceName);

      // Log the action.
      System.out.println("Deleted Namespace: " + namespaceName.toString());
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 서비스 디렉터리 Node.js SDK를 설치합니다.

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

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

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

// Build the namespace name
const namespaceName = registrationServiceClient.namespacePath(
  projectId,
  locationId,
  namespaceId
);

async function deleteNamespace() {
  await registrationServiceClient.deleteNamespace({
    name: namespaceName,
  });

  console.log(`Deleted namespace: ${namespaceName}`);
}

deleteNamespace();

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 서비스 디렉터리 PHP SDK를 설치합니다.

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;

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

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

// Run request.
$namespaceName = RegistrationServiceClient::namespaceName($projectId, $locationId, $namespaceId);
$client->deleteNamespace($namespaceName);

// Print results.
printf('Deleted Namespace: %s' . PHP_EOL, $namespaceName);

Python

이 코드를 실행하려면 먼저 Python 개발 환경을 설정하고 서비스 디렉터리 Python SDK를 설치합니다.

def delete_namespace(project_id, location_id, namespace_id):
    """Deletes a namespace in the given location."""

    client = servicedirectory_v1.RegistrationServiceClient()

    namespace_name = client.namespace_path(project_id, location_id, namespace_id)

    client.delete_namespace(name=namespace_name)

    print(f'Deleted namespace {namespace_name}.')

Ruby

이 코드를 실행하려면 먼저 Ruby 개발 환경을 설정하고 서비스 디렉터리 Ruby SDK를 설치합니다.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the namespace"
# namespace = "The name of the namespace"

require "google/cloud/service_directory"

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

# The path of the namespace
namespace_name = registration_service.namespace_path(
  project: project, location: location, namespace: namespace
)

# Use the Service Directory API to delete the namespace
registration_service.delete_namespace name: namespace_name
puts "Deleted namespace: #{namespace_name}"

다음 단계

  • DNS를 사용하여 서비스를 쿼리할 수 있도록 서비스 디렉터리 영역을 구성하려면 서비스 디렉터리 영역을 참조하세요.
  • 서비스 디렉터리에 대한 개요는 서비스 디렉터리 개요를 참조하세요.
  • 서비스 디렉터리를 사용할 때 발생할 수 있는 일반적인 문제에 대한 해결책을 찾으려면 문제해결을 참조하세요.