구독 분리

구독을 만들 때 주제에 구독을 연결하면 구독자가 구독에서 메시지를 수신할 수 있습니다. 구독자가 메시지를 받지 못하도록 하려면 주제에서 구독을 분리하면 됩니다.

시작하기 전에

필수 역할 및 권한

구독을 분리하는 데 필요한 권한을 얻으려면 관리자에게 주제에 대한 Pub/Sub 편집자 (roles/pubsub.editor) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 pubsub.topics.detachSubscription 권한이 포함되어 있으며, 구독을 분리하는 데 필요합니다.

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 가져올 수도 있습니다.

프로젝트 수준 및 개별 리소스 수준에서 액세스 제어를 구성할 수 있습니다. 한 프로젝트에서 구독을 만들고 이를 다른 프로젝트에 있는 주제에 연결할 수 있습니다. 각 프로젝트에 필요한 권한이 있는지 확인합니다.

주제에서 구독 분리

Console, Google Cloud CLI, 클라이언트 라이브러리, Pub/Sub API를 사용하여 주제에서 구독을 분리할 수 있습니다. Cloud de Confiance

콘솔

구독을 분리하려면 다음 단계를 따르세요.

  1. 콘솔에서 주제 페이지로 이동합니다. Cloud de Confiance

    주제로 이동

  2. 구독을 분리하려는 주제를 선택합니다.

  3. 구독 탭에서 분리할 구독을 선택합니다.

  4. 구독 세부정보 페이지에서 분리를 클릭합니다.

  5. 표시되는 대화상자에서 분리를 다시 클릭합니다.

gcloud

  1. 콘솔에서 Cloud Shell을 활성화합니다. Cloud de Confiance

    Cloud Shell 활성화

    콘솔 하단에 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. Cloud de Confiance Cloud Shell은 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  2. 구독을 분리하려면 gcloud pubsub topics detach-subscription 명령어를 사용합니다.

    gcloud pubsub topics detach-subscription SUBSCRIPTION_ID

    요청이 성공하면 명령줄에 확인 메시지가 표시됩니다.

    Detached subscription [SUBSCRIPTION_ID].

REST

구독을 분리하려면 projects.subscriptions.detach 메서드를 사용합니다.

요청:

요청은 Authorization 헤더의 액세스 토큰으로 인증해야 합니다. 현재 애플리케이션 기본 사용자 인증 정보에 대해 액세스 토큰을 가져오려면 gcloud auth application-default print-access-token 명령어를 사용합니다.

POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:detach
Authorization: Bearer ACCESS_TOKEN

각 항목의 의미는 다음과 같습니다.

  • PROJECT_ID: 프로젝트 ID
  • SUBSCRIPTION_ID: 구독 ID

응답:

요청이 성공하면 응답은 빈 JSON 객체입니다.

C++

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 C++ 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C++ API 참고 문서를 확인하세요.

namespace pubsub = ::google::cloud::pubsub;
namespace pubsub_admin = ::google::cloud::pubsub_admin;
[](pubsub_admin::TopicAdminClient client, std::string const& project_id,
   std::string const& subscription_id) {
  google::pubsub::v1::DetachSubscriptionRequest request;
  request.set_subscription(
      pubsub::Subscription(project_id, subscription_id).FullName());
  auto response = client.DetachSubscription(request);
  if (!response.ok()) throw std::move(response).status();

  std::cout << "The subscription was successfully detached: "
            << response->DebugString() << "\n";
}

C#

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 C# 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C# API 참고 문서를 확인하세요.


using Google.Cloud.PubSub.V1;
using System;

public class DetachSubscriptionSample
{
    public void DetachSubscription(string projectId, string subscriptionId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();

        DetachSubscriptionRequest detachSubscriptionRequest = new DetachSubscriptionRequest
        {
            SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
        };

        publisher.DetachSubscription(detachSubscriptionRequest);

        Console.WriteLine($"Subscription {subscriptionId} is detached.");
    }
}

Go

다음 샘플은 Go Pub/Sub 클라이언트 라이브러리 (v2)의 주요 버전을 사용합니다. 아직 v1 라이브러리를 사용하고 있다면 v2로의 마이그레이션 가이드를 참조하세요. v1 코드 샘플 목록을 보려면 지원 중단된 코드 샘플을 참조하세요.

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Go API 참고 문서를 참조하세요.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub/v2"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

func detachSubscription(w io.Writer, projectID, subName string) error {
	// projectID is the project which contains the topic you manage.
	// This might differ from the project which contains the subscription
	// you wish to detach, which can exist in any GCP project.
	// projectID := "my-project-id"
	// subName := "projects/some-project/subscriptions/my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	// Call DetachSubscription, which detaches a subscription from
	// a topic. This can only be done if you have the
	// `pubsub.topics.detachSubscription` role on the topic the
	// subscription is attached to.
	req := &pubsubpb.DetachSubscriptionRequest{
		Subscription: subName,
	}
	_, err = client.TopicAdminClient.DetachSubscription(ctx, req)
	if err != nil {
		return fmt.Errorf("detach subscription failed: %w", err)
	}

	fmt.Fprintf(w, "Detached subscription %s", subName)
	return nil
}

자바

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Java 설정 안내를 따르세요. 자세한 내용은 Pub/Sub 자바 API 참고 문서를 참조하세요.

import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.DetachSubscriptionRequest;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.SubscriptionName;
import java.io.IOException;

public class DetachSubscriptionExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    // Choose an existing subscription.
    String subscriptionId = "your-subscription-id";

    detachSubscriptionExample(projectId, subscriptionId);
  }

  public static void detachSubscriptionExample(String projectId, String subscriptionId)
      throws IOException {
    SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);

    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      topicAdminClient.detachSubscription(
          DetachSubscriptionRequest.newBuilder()
              .setSubscription(subscriptionName.toString())
              .build());
    }

    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
      if (subscription.getDetached()) {
        System.out.println("Subscription is detached.");
      } else {
        System.out.println("Subscription is NOT detached.");
      }
    }
  }
}

Node.js

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Node.js API 참고 문서를 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function detachSubscription(subscriptionNameOrId) {
  // Gets the status of the existing subscription
  const sub = pubSubClient.subscription(subscriptionNameOrId);
  const [detached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`,
  );

  await pubSubClient.detachSubscription(subscriptionNameOrId);
  console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);

  const [updatedDetached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`,
  );
}

Node.ts

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Node.js API 참고 문서를 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID';

// Imports the Google Cloud client library
import {PubSub} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function detachSubscription(subscriptionNameOrId: string) {
  // Gets the status of the existing subscription
  const sub = pubSubClient.subscription(subscriptionNameOrId);
  const [detached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`,
  );

  await pubSubClient.detachSubscription(subscriptionNameOrId);
  console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);

  const [updatedDetached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`,
  );
}

PHP

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 PHP 설정 안내를 따르세요. 자세한 내용은 Pub/Sub PHP API 참고 문서를 참조하세요.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Detach a Pub/Sub subscription from a topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function detach_subscription($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $subscription->detach();

    printf('Subscription detached: %s' . PHP_EOL, $subscription->name());
}

Python

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Python API 참고 문서를 참조하세요.

from google.api_core.exceptions import GoogleAPICallError, RetryError
from google.cloud import pubsub_v1

# TODO(developer): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

publisher_client = pubsub_v1.PublisherClient()
subscriber_client = pubsub_v1.SubscriberClient()
subscription_path = subscriber_client.subscription_path(project_id, subscription_id)

try:
    publisher_client.detach_subscription(
        request={"subscription": subscription_path}
    )
except (GoogleAPICallError, RetryError, ValueError, Exception) as err:
    print(err)

subscription = subscriber_client.get_subscription(
    request={"subscription": subscription_path}
)
if subscription.detached:
    print(f"{subscription_path} is detached.")
else:
    print(f"{subscription_path} is NOT detached.")

Ruby

다음 샘플은 Ruby Pub/Sub 클라이언트 라이브러리 v3을 사용합니다. 아직 v2 라이브러리를 사용하고 있다면 v3으로의 마이그레이션 가이드를 참조하세요. Ruby v2 코드 샘플 목록을 보려면 지원 중단된 코드 샘플을 참조하세요.

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Ruby 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Ruby API 참고 문서를 참조하세요.

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::PubSub.new
topic_admin = pubsub.topic_admin
subscription_admin = pubsub.subscription_admin
subscription_path = pubsub.subscription_path subscription_id

topic_admin.detach_subscription subscription: subscription_path
sleep 120
subscription = subscription_admin.get_subscription \
  subscription: subscription_path

if subscription.detached
  puts "Subscription is detached."
else
  puts "Subscription is NOT detached."
end

Pub/Sub 서비스가 주제에서 구독 분리를 완료하는 데 몇 분 정도 걸릴 수 있습니다.

Pub/Sub 서비스가 주제에서 구독을 분리하면 Pub/Sub 서비스가 구독에 대해 유지하는 모든 메시지를 삭제합니다. 구독에서 이러한 메시지를 검색하거나 주제에 구독을 다시 연결할 수 없습니다. 프로젝트 할당량을 확보하려면 구독을 삭제하세요. Cloud de Confiance

구독과 주제가 다른 Cloud de Confiance 프로젝트에 있는 경우 Pub/Sub 서비스는 두 프로젝트의 감사 로그에 항목을 추가합니다.

다음 단계