サブスクリプションの接続解除

サブスクリプションを作成するとき、サブスクリプションをトピックに接続すると、サブスクライバーはサブスクリプションからメッセージを受信できます。サブスクライバーがメッセージの受信止めるには、トピックからサブスクリプションを切断します。

サブスクリプションを接続解除するには、トピックに対する pubsub.topics.detachSubscription 権限が必要です。サブスクリプションの接続解除は、サブスクリプションに対する権限なしで行えます。これは、サブスクリプションとは別のプロジェクトにあるトピックを管理する場合に使用します。詳細については、Pub/Sub のアクセス制御をご覧ください。

準備

必要なロールと権限

サブスクリプションの接続解除と管理に必要な権限を取得するには、トピックまたはプロジェクトに対する Pub/Sub 編集者 roles/pubsub.editor)の IAM ロールを付与するように管理者に依頼してください。ロールの付与の詳細については、アクセスの管理をご覧ください。

この事前定義ロールには、サブスクリプションの接続解除と管理に必要な権限が含まれています。必要な権限を正確に確認するには、[必要な権限] セクションを開いてください。

必要な権限

サブスクリプションを接続解除して管理するには、次の権限が必要です。

  • サブスクリプションから pull する: pubsub.subscriptions.consume
  • サブスクリプションを作成する: pubsub.subscriptions.create
  • サブスクリプションを削除する: pubsub.subscriptions.delete
  • サブスクリプションを取得する: pubsub.subscriptions.get
  • サブスクリプションを一覧表示する: pubsub.subscriptions.list
  • サブスクリプションを更新する: pubsub.subscriptions.update
  • サブスクリプションをトピックに接続する: pubsub.topics.attachSubscription
  • サブスクリプションの IAM ポリシーを取得する: pubsub.subscriptions.getIamPolicy
  • サブスクリプションの IAM ポリシーを構成する: pubsub.subscriptions.setIamPolicy

カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

アクセス制御は、プロジェクト レベルと個々のリソースレベルで構成できます。あるプロジェクトにサブスクリプションを作成し、別のプロジェクトにあるトピックにアタッチできます。プロジェクトごとに必要な権限があることを確認します。

トピックからサブスクリプションの接続を解除する

Google Cloud コンソール、Google Cloud CLI、クライアント ライブラリ、または Pub/Sub API を使用して、トピックからサブスクリプションを接続解除できます。

Console

サブスクリプションを切断する手順は、次のとおりです。

  1. Google Cloud コンソールの トピック ページに移動します。

    [トピック] に移動

  2. サブスクリプションの接続を解除するトピックを選択します。

  3. [サブスクリプション] タブで、接続解除するサブスクリプションを選択します。

  4. [サブスクリプションの詳細] ページで [接続解除] をクリックします。

  5. 表示されたダイアログで、再度 [接続解除] をクリックします。

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 detach-subscription コマンドを使用します。

    gcloud pubsub topics detach-subscription SUBSCRIPTION_ID

    リクエストが成功すると、コマンドラインに確認メッセージが表示されます。

    Detached subscription [SUBSCRIPTION_ID].

REST

サブスクリプションを切断するには、projects.subscriptions.detach メソッドを使用します。

リクエスト:

リクエストは、Authorization ヘッダー内のアクセス トークンにより認証を受ける必要があります。現在のアプリケーションのデフォルト認証情報のアクセス トークンを取得するには、gcloud auth application-default print-access-token コマンドを使用します。

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

ここで

  • PROJECT_ID はプロジェクト ID です。
  • SUBSCRIPTION_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& subscription_id) {
      google::pubsub::v1::DetachSubscriptionRequest request;
      request.set_subscription(
          pubsub::Subscription(project_id, subscription_id).FullName());
      auto response = client.DetachSubscription(request);
      if (!response.ok()) throw std::move(response).status();
    
      std::cout << "The subscription was successfully detached: "
                << response->DebugString() << "\n";
    }

    C#

    このサンプルを試す前に、Pub/Sub クイックスタート: クライアント ライブラリの使用にある C# 向けの手順に従って設定を行ってください。 詳細については、Pub/Sub C# API のリファレンス ドキュメントをご覧ください。

    Pub/Sub に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    
    using Google.Cloud.PubSub.V1;
    using System;
    
    public class DetachSubscriptionSample
    {
        public void DetachSubscription(string projectId, string subscriptionId)
        {
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
    
            DetachSubscriptionRequest detachSubscriptionRequest = new DetachSubscriptionRequest
            {
                SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
            };
    
            publisher.DetachSubscription(detachSubscriptionRequest);
    
            Console.WriteLine($"Subscription {subscriptionId} is detached.");
        }
    }

    Go

    このサンプルを試す前に、Pub/Sub クイックスタート: クライアント ライブラリの使用にある Go 向けの手順に従って設定を行ってください。 詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

    Pub/Sub に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/pubsub"
    )
    
    func detachSubscription(w io.Writer, projectID, subName string) error {
    	// projectID is the project which contains the topic you manage.
    	// This might differ from the project which contains the subscription
    	// you wish to detach, which can exist in any GCP project.
    	// projectID := "my-project-id"
    	// subName := "projects/some-project/subscriptions/my-sub"
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	// Call DetachSubscription, which detaches a subscription from
    	// a topic. This can only be done if you have the
    	// `pubsub.topics.detachSubscription` role on the topic.
    	_, err = client.DetachSubscription(ctx, subName)
    	if err != nil {
    		return fmt.Errorf("detach subscription failed: %w", err)
    	}
    
    	fmt.Fprintf(w, "Detached subscription %s", subName)
    	return nil
    }
    

    Java

    このサンプルを試す前に、Pub/Sub クイックスタート: クライアント ライブラリの使用にある Java 向けの手順に従って設定を行ってください。 詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。

    Pub/Sub に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
    import com.google.cloud.pubsub.v1.TopicAdminClient;
    import com.google.pubsub.v1.DetachSubscriptionRequest;
    import com.google.pubsub.v1.Subscription;
    import com.google.pubsub.v1.SubscriptionName;
    import java.io.IOException;
    
    public class DetachSubscriptionExample {
      public static void main(String... args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        // Choose an existing subscription.
        String subscriptionId = "your-subscription-id";
    
        detachSubscriptionExample(projectId, subscriptionId);
      }
    
      public static void detachSubscriptionExample(String projectId, String subscriptionId)
          throws IOException {
        SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
    
        try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
          topicAdminClient.detachSubscription(
              DetachSubscriptionRequest.newBuilder()
                  .setSubscription(subscriptionName.toString())
                  .build());
        }
    
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
          Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
          if (subscription.getDetached()) {
            System.out.println("Subscription is detached.");
          } else {
            System.out.println("Subscription is NOT detached.");
          }
        }
      }
    }

    Node.js

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const subscriptionNameOrId = 'YOUR_EXISTING_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 detachSubscription(subscriptionNameOrId) {
      // Gets the status of the existing subscription
      const sub = pubSubClient.subscription(subscriptionNameOrId);
      const [detached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`
      );
    
      await pubSubClient.detachSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);
    
      const [updatedDetached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`
      );
    }

    Node.js

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const subscriptionNameOrId = 'YOUR_EXISTING_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 detachSubscription(subscriptionNameOrId: string) {
      // Gets the status of the existing subscription
      const sub = pubSubClient.subscription(subscriptionNameOrId);
      const [detached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`
      );
    
      await pubSubClient.detachSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);
    
      const [updatedDetached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`
      );
    }

    PHP

    このサンプルを試す前に、Pub/Sub クイックスタート: クライアント ライブラリの使用にある PHP 向けの手順に従って設定を行ってください。 詳細については、Pub/Sub PHP API のリファレンス ドキュメントをご覧ください。

    Pub/Sub に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

    Python

    このサンプルを試す前に、Pub/Sub クイックスタート: クライアント ライブラリの使用にある Python 向けの手順に従って設定を行ってください。 詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

    Pub/Sub に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    from google.api_core.exceptions import GoogleAPICallError, RetryError
    from google.cloud import pubsub_v1
    
    # TODO(developer): Choose an existing subscription.
    # project_id = "your-project-id"
    # subscription_id = "your-subscription-id"
    
    publisher_client = pubsub_v1.PublisherClient()
    subscriber_client = pubsub_v1.SubscriberClient()
    subscription_path = subscriber_client.subscription_path(project_id, subscription_id)
    
    try:
        publisher_client.detach_subscription(
            request={"subscription": subscription_path}
        )
    except (GoogleAPICallError, RetryError, ValueError, Exception) as err:
        print(err)
    
    subscription = subscriber_client.get_subscription(
        request={"subscription": subscription_path}
    )
    if subscription.detached:
        print(f"{subscription_path} is detached.")
    else:
        print(f"{subscription_path} is NOT detached.")

    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.detach
    
    sleep 120
    subscription.reload!
    if subscription.detached?
      puts "Subscription is detached."
    else
      puts "Subscription is NOT detached."
    end

    Pub/Sub サービスがトピックからサブスクリプションを接続解除するまで数分かかる場合があります。

    Pub/Sub サービスがトピックからサブスクリプションを接続解除すると、Pub/Sub サービスは、サブスクリプション用に保持するメッセージをすべて削除します。サブスクリプションからこれらのメッセージを取得することや、サブスクリプションをトピックに再接続することはできません。Google Cloud プロジェクトの割り当てを解放するには、サブスクリプションを削除します。

    サブスクリプションとトピックが異なる Google Cloud プロジェクトにある場合、Pub/Sub サービスは、両方のプロジェクトの監査ログにエントリを追加します。

    次のステップ

    • gcloud コマンドを使用して、サブスクリプションを作成または変更する。
    • REST API を使用してサブスクリプションを作成または変更する。