주제 삭제

이 문서에서는 Pub/Sub 주제를 삭제하는 방법을 설명합니다. 주제를 삭제하려면 Google Cloud 콘솔, Google CLI, 클라이언트 라이브러리, Pub/Sub API를 사용할 수 있습니다.

시작하기 전에

필수 역할 및 권한

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

이 사전 정의된 역할에는 주제를 삭제하고 관리하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

주제를 삭제하고 관리하려면 다음 권한이 필요합니다.

  • 주제 만들기: pubsub.topics.create
  • 주제 삭제: pubsub.topics.delete
  • 주제에서 구독 분리: pubsub.topics.detachSubscription
  • 주제 가져오기: pubsub.topics.get
  • 주제 나열: pubsub.topics.list
  • 주제에 게시: pubsub.topics.publish
  • 주제 업데이트: pubsub.topics.update
  • 주제의 IAM 정책 가져오기: pubsub.topics.getIamPolicy
  • 주제의 IAM 정책 구성: pubsub.topics.setIamPolicy

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

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

주제 삭제

주제를 삭제해도 구독은 삭제되지 않습니다. 구독의 메시지 백로그는 구독자가 사용할 수 있습니다. 주제를 삭제하면 해당 구독에 주제 이름 _deleted-topic_이 지정됩니다. 삭제 후 얼마 지나지 않아 삭제한 것과 이름이 같은 주제를 생성하면 일시적으로 오류가 발생합니다.

콘솔

  1. Google Cloud 콘솔에서 Pub/Sub 주제 페이지로 이동합니다.

  2. 주제로 이동

  3. 주제를 선택하고 작업 더보기를 클릭합니다.

  4. 삭제를 클릭합니다.

    주제 삭제 창이 나타납니다.

  5. delete를 입력한 후 삭제를 클릭합니다.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 주제를 삭제하려면 gcloud pubsub topics delete 명령어를 사용합니다.

    gcloud pubsub topics delete TOPIC_ID
  3. REST

    주제를 삭제하려면 projects.topics.delete 메서드를 사용합니다.

    요청:

    요청은 Authorization 헤더의 액세스 토큰으로 인증해야 합니다. 현재 애플리케이션 기본 사용자 인증 정보에 대한 액세스 토큰을 얻는 방법은 다음과 같습니다. gcloud auth application-default print-access-token.

    DELETE https://pubsub.googleapis.com/v1/projects/PROJECT_ID/topics/TOPIC_ID
    Authorization: Bearer ACCESS_TOKEN
      

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

    • PROJECT_ID는 프로젝트 ID입니다.
    • TOPIC_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& topic_id) {
      auto status =
          client.DeleteTopic(pubsub::Topic(project_id, topic_id).FullName());
      // Note that kNotFound is a possible result when the library retries.
      if (status.code() == google::cloud::StatusCode::kNotFound) {
        std::cout << "The topic was not found\n";
        return;
      }
      if (!status.ok()) throw std::runtime_error(status.message());
    
      std::cout << "The topic was successfully deleted\n";
    }

    C#

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

    
    using Google.Cloud.PubSub.V1;
    
    public class DeleteTopicSample
    {
        public void DeleteTopic(string projectId, string topicId)
        {
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
            publisher.DeleteTopic(topicName);
        }
    }

    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 delete(w io.Writer, projectID, topicID string) error {
    	// projectID := "my-project-id"
    	// topicID := "my-topic"
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &pubsubpb.DeleteTopicRequest{
    		Topic: fmt.Sprintf("projects/%s/topics/%s", projectID, topicID),
    	}
    	err = client.TopicAdminClient.DeleteTopic(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to delete topic: %w", err)
    	}
    	fmt.Fprintln(w, "Deleted topic")
    	return nil
    }
    

    자바

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

    
    import com.google.api.gax.rpc.NotFoundException;
    import com.google.cloud.pubsub.v1.TopicAdminClient;
    import com.google.pubsub.v1.TopicName;
    import java.io.IOException;
    
    public class DeleteTopicExample {
      public static void main(String... args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String topicId = "your-topic-id";
    
        deleteTopicExample(projectId, topicId);
      }
    
      public static void deleteTopicExample(String projectId, String topicId) throws IOException {
        try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
          TopicName topicName = TopicName.of(projectId, topicId);
          try {
            topicAdminClient.deleteTopic(topicName);
            System.out.println("Deleted topic.");
          } catch (NotFoundException e) {
            System.out.println(e.getMessage());
          }
        }
      }
    }

    Node.js

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

    /**
     * TODO(developer): Uncomment this variable before running the sample.
     */
    // const topicNameOrId = 'YOUR_TOPIC_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 deleteTopic(topicNameOrId) {
      /**
       * TODO(developer): Uncomment the following line to run the sample.
       */
      // const topicName = 'my-topic';
    
      // Deletes the topic
      await pubSubClient.topic(topicNameOrId).delete();
      console.log(`Topic ${topicNameOrId} deleted.`);
    }

    Node.ts

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

    /**
     * TODO(developer): Uncomment this variable before running the sample.
     */
    // const topicNameOrId = 'YOUR_TOPIC_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 deleteTopic(topicNameOrId: string) {
      /**
       * TODO(developer): Uncomment the following line to run the sample.
       */
      // const topicName = 'my-topic';
    
      // Deletes the topic
      await pubSubClient.topic(topicNameOrId).delete();
      console.log(`Topic ${topicNameOrId} deleted.`);
    }

    PHP

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

    use Google\Cloud\PubSub\PubSubClient;
    
    /**
     * Creates a Pub/Sub topic.
     *
     * @param string $projectId  The Google project ID.
     * @param string $topicName  The Pub/Sub topic name.
     */
    function delete_topic($projectId, $topicName)
    {
        $pubsub = new PubSubClient([
            'projectId' => $projectId,
        ]);
        $topic = $pubsub->topic($topicName);
        $topic->delete();
    
        printf('Topic deleted: %s' . PHP_EOL, $topic->name());
    }

    Python

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

    from google.cloud import pubsub_v1
    
    # TODO(developer)
    # project_id = "your-project-id"
    # topic_id = "your-topic-id"
    
    publisher = pubsub_v1.PublisherClient()
    topic_path = publisher.topic_path(project_id, topic_id)
    
    publisher.delete_topic(request={"topic": topic_path})
    
    print(f"Topic deleted: {topic_path}")

    Ruby

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

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

    # topic_id = "your-topic-id"
    
    pubsub = Google::Cloud::PubSub.new
    topic_admin = pubsub.topic_admin
    
    topic_admin.delete_topic topic: pubsub.topic_path(topic_id)
    
    puts "Topic #{topic_id} deleted."

다음 단계