删除主题

本文档介绍了如何删除 Pub/Sub 主题。如需删除主题,您可以使用 Google Cloud 控制台、Google Cloud CLI、客户端库或 Pub/Sub API。

准备工作

所需的角色和权限

如需获得删除和管理主题所需的权限,请让您的管理员为您授予主题或项目的 Pub/Sub Editor(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

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++

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C++ 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C++ API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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#

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/pubsub"
    )
    
    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()
    
    	t := client.Topic(topicID)
    	if err := t.Delete(ctx); err != nil {
    		return fmt.Errorf("Delete: %w", err)
    	}
    	fmt.Fprintf(w, "Deleted topic: %v\n", t)
    	return nil
    }
    

    Java

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    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

    /**
     * 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.js

    /**
     * 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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub PHP API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    # topic_id = "your-topic-id"
    
    pubsub = Google::Cloud::Pubsub.new
    
    topic = pubsub.topic topic_id
    topic.delete
    
    puts "Topic #{topic_id} deleted."

    后续步骤