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

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

始める前に

必要なロールと権限

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

この事前定義ロールには、 pubsub.topics.detachSubscription 権限が含まれています。 この権限は、 サブスクリプションを切断するために必要です。

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

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

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

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

コンソール

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

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

    [トピック] に移動

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

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

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

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

gcloud

  1. コンソールで Cloud Shell をアクティブにします。 Google Cloud

    Cloud Shell をアクティブにする

    コンソールの下部にある Google Cloud Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です 。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています 。セッションが初期化されるまで数秒かかることがあります。

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

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

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#

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


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

次のサンプルでは、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 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 the
	// subscription is attached to.
	req := &pubsubpb.DetachSubscriptionRequest{
		Subscription: subName,
	}
	_, err = client.TopicAdminClient.DetachSubscription(ctx, req)
	if err != nil {
		return fmt.Errorf("detach subscription failed: %w", err)
	}

	fmt.Fprintf(w, "Detached subscription %s", subName)
	return nil
}

Java

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

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

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API リファレンス ドキュメントをご覧ください。

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

このサンプルを試す前に、 クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。 詳細については、Pub/Sub Node.js API リファレンス ドキュメントをご覧ください。

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

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

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

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

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

次のサンプルでは、Ruby Pub/Sub クライアント ライブラリ v3 を使用しています。v2 ライブラリをまだ使用している場合は、 v3 への移行ガイドをご覧ください。 Ruby v2 コードサンプルのリストを表示するには、 非推奨のコードサンプルをご覧ください。

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

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::PubSub.new
topic_admin = pubsub.topic_admin
subscription_admin = pubsub.subscription_admin
subscription_path = pubsub.subscription_path subscription_id

topic_admin.detach_subscription subscription: subscription_path
sleep 120
subscription = subscription_admin.get_subscription \
  subscription: subscription_path

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 を使用してサブスクリプションを作成または変更する。