刪除訂閱項目

您可以使用 Google Cloud 控制台、Google Cloud CLI、用戶端程式庫或 Pub/Sub API 刪除 Pub/Sub 訂閱項目。

本文將說明如何在 Pub/Sub 中刪除訂閱項目。

事前準備

必要角色和權限

如要取得刪除訂閱所需的權限,請要求管理員為您授予訂閱或包含訂閱的專案的 Pub/Sub 編輯者 (roles/pubsub.editor) IAM 角色。

這個預先定義的角色具備刪除訂閱項目所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • pubsub.subscriptions.delete
  • pubsub.subscriptions.list
    • 只有在使用 Google Cloud 控制台刪除訂閱項目時,才需要這項權限。

您或許還可透過其他自訂角色預先定義的 Pub/Sub 角色取得這些權限。

刪除訂閱項目

控制台

  1. 在 Google Cloud 控制台中,前往「訂閱項目」頁面。

    前往「訂閱項目」頁面

  2. 選取要刪除的訂閱項目。
  3. 點選「刪除」。

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 subscriptions delete 指令:

    gcloud pubsub subscriptions delete SUBSCRIPTION_ID

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

    在嘗試這個範例之前,請先按照 Pub/Sub 快速入門:使用用戶端程式庫中的操作說明設定 C++。詳情請參閱 Pub/Sub C++ API 參考說明文件

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    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#

    在嘗試這個範例之前,請先按照 Pub/Sub 快速入門:使用用戶端程式庫中的操作說明設定 C#。詳情請參閱 Pub/Sub C# API 參考說明文件

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    
    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

    在嘗試這個範例之前,請先按照 Pub/Sub 快速入門:使用用戶端程式庫中的操作說明設定 Go。詳情請參閱 Pub/Sub Go API 參考說明文件

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/pubsub"
    )
    
    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()
    
    	sub := client.Subscription(subID)
    	if err := sub.Delete(ctx); err != nil {
    		return fmt.Errorf("Delete: %w", err)
    	}
    	fmt.Fprintf(w, "Subscription %q deleted.", subID)
    	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.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

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

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

    在嘗試這個範例之前,請先按照 Pub/Sub 快速入門:使用用戶端程式庫中的操作說明設定 PHP。詳情請參閱 Pub/Sub PHP API 參考說明文件

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    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

    在嘗試這個範例之前,請先按照 Pub/Sub 快速入門:使用用戶端程式庫中的操作說明設定 Python。詳情請參閱 Pub/Sub Python API 參考說明文件

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    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

    在嘗試這個範例之前,請先按照 Pub/Sub 快速入門:使用用戶端程式庫中的操作說明設定 Ruby。詳情請參閱 Pub/Sub Ruby API 參考說明文件

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    # subscription_id = "your-subscription-id"
    
    pubsub = Google::Cloud::Pubsub.new
    
    subscription = pubsub.subscription subscription_id
    subscription.delete
    
    puts "Subscription #{subscription_id} deleted."

    您可以建立與剛剛刪除的訂閱項目相同名稱的訂閱項目。不過,新建立的訂閱項目與先前刪除的訂閱項目完全無關。舊訂閱項目的郵件不會傳送至新訂閱項目。

    後續步驟