删除订阅

您可以使用 Cloud de Confiance 控制台、Google Cloud CLI、客户端库或 Pub/Sub API 删除 Pub/Sub 订阅。

本文档讨论了如何在 Pub/Sub 中删除订阅。

准备工作

所需的角色和权限

如需获得删除订阅所需的权限,请让管理员向您授予订阅或包含该订阅的项目的 Pub/Sub Editor (roles/pubsub.editor) IAM 角色。

此预定义角色包含删除订阅所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

  • pubsub.subscriptions.delete
  • pubsub.subscriptions.list
    • 只有使用 Cloud de Confiance 控制台删除订阅时,才需要此权限。

您也可以使用其他自定义角色Pub/Sub 预定义角色来获取这些权限。

删除订阅

控制台

  1. 在 Cloud de Confiance 控制台中,前往订阅页面。

    前往“订阅”页面

  2. 选择要删除的订阅。
  3. 点击删除

gcloud

  1. In the Cloud de Confiance console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Cloud de Confiance 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 subscriptions delete 命令:

    gcloud pubsub subscriptions delete SUBSCRIPTION_ID
  3. REST

    如需删除订阅,请使用 projects.subscriptions.delete 方法:

    请求:

    必须使用 Authorization 标头中的访问令牌对请求进行身份验证。如需获取当前应用默认凭据的访问令牌,请运行以下命令:gcloud auth application-default print-access-token

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

    其中:

    • PROJECT_ID 是项目 ID。
    • SUBSCRIPTION_ID 是您的订阅 ID。

    回答:

    如果请求成功,响应将为空的 JSON 对象。

    删除操作是最终一致的操作,因此其他进程可能需要一段时间才能看到其效果。

    C++

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

    namespace pubsub_admin = ::google::cloud::pubsub_admin;
    namespace pubsub = ::google::cloud::pubsub;
    [](pubsub_admin::SubscriptionAdminClient client,
       std::string const& project_id, std::string const& subscription_id) {
      auto status = client.DeleteSubscription(
          pubsub::Subscription(project_id, subscription_id).FullName());
      // Note that kNotFound is a possible result when the library retries.
      if (status.code() == google::cloud::StatusCode::kNotFound) {
        std::cout << "The subscription was not found\n";
        return;
      }
      if (!status.ok()) throw std::runtime_error(status.message());
    
      std::cout << "The subscription was successfully deleted\n";

    C#

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

    
    using Google.Cloud.PubSub.V1;
    
    public class DeleteSubscriptionSample
    {
        public void DeleteSubscription(string projectId, string subscriptionId)
        {
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
            subscriber.DeleteSubscription(subscriptionName);
        }
    }

    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, subID string) error {
    	// projectID := "my-project-id"
    	// subID := "my-sub"
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &pubsubpb.DeleteSubscriptionRequest{
    		Subscription: fmt.Sprintf("projects/%s/subscriptions/%s", projectID, subID),
    	}
    	if err := client.SubscriptionAdminClient.DeleteSubscription(ctx, req); err != nil {
    		return fmt.Errorf("Delete: %w", err)
    	}
    	fmt.Fprintf(w, "Subscription %q deleted.", subID)
    	return nil
    }
    

    Java

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

    
    import com.google.api.gax.rpc.NotFoundException;
    import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
    import com.google.pubsub.v1.SubscriptionName;
    import java.io.IOException;
    
    public class DeleteSubscriptionExample {
    
      public static void main(String... args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String subscriptionId = "your-subscription-id";
    
        deleteSubscriptionExample(projectId, subscriptionId);
      }
    
      public static void deleteSubscriptionExample(String projectId, String subscriptionId)
          throws IOException {
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
          SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
          try {
            subscriptionAdminClient.deleteSubscription(subscriptionName);
            System.out.println("Deleted subscription.");
          } 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 subscriptionNameOrId = 'YOUR_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 deleteSubscription(subscriptionNameOrId) {
      // Deletes the subscription
      await pubSubClient.subscription(subscriptionNameOrId).delete();
      console.log(`Subscription ${subscriptionNameOrId} deleted.`);
    }

    Node.ts

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

    /**
     * TODO(developer): Uncomment this variable before running the sample.
     */
    // const subscriptionNameOrId = 'YOUR_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 deleteSubscription(subscriptionNameOrId: string) {
      // Deletes the subscription
      await pubSubClient.subscription(subscriptionNameOrId).delete();
      console.log(`Subscription ${subscriptionNameOrId} deleted.`);
    }

    PHP

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

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

    Python

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

    from google.cloud import pubsub_v1
    
    # TODO(developer)
    # project_id = "your-project-id"
    # subscription_id = "your-subscription-id"
    
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path(project_id, subscription_id)
    
    # Wrap the subscriber in a 'with' block to automatically call close() to
    # close the underlying gRPC channel when done.
    with subscriber:
        subscriber.delete_subscription(request={"subscription": subscription_path})
    
    print(f"Subscription deleted: {subscription_path}.")

    Ruby

    以下示例使用 Ruby Pub/Sub 客户端库 v3。如果您仍在使用 v2 库,请参阅 迁移到 v3 的指南。如需查看 Ruby v2 代码示例的列表,请参阅 已弃用的代码示例

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

    # subscription_id = "your-subscription-id"
    
    pubsub = Google::Cloud::PubSub.new
    subscription_admin = pubsub.subscription_admin
    
    subscription_admin.delete_subscription \
      subscription: pubsub.subscription_path(subscription_id)
    
    puts "Subscription #{subscription_id} deleted."

您可以创建与刚刚删除的订阅同名的订阅。不过,新创建的订阅完全独立于之前删除的订阅。发往旧订阅的消息不会递送到新订阅。

后续步骤