刪除訂閱項目

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

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

事前準備

必要角色和權限

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

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

所需權限

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

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

刪除訂閱項目

控制台

  1. 前往 Google Cloud 控制台的「Subscriptions」(訂閱項目) 頁面。

    前往「訂閱項目」頁面

  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
  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)。如果您仍在使用第 1 版程式庫,請參閱第 2 版遷移指南。如要查看第 1 版程式碼範例清單,請參閱 已淘汰的程式碼範例

    在試用這個範例之前,請先按照快速入門:使用用戶端程式庫中的 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。如果您仍在使用第 2 版程式庫,請參閱 第 3 版遷移指南。如要查看 Ruby 第 2 版程式碼範例清單,請參閱 已淘汰的程式碼範例

    在試用這個範例之前,請先按照快速入門:使用用戶端程式庫的操作說明設定 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."

您可以建立與剛刪除的訂閱項目同名的訂閱項目。不過,新建立的訂閱項目與先前刪除的項目完全無關。系統不會將傳送給舊訂閱項目的訊息傳送至新訂閱項目。

後續步驟