サブスクリプションの一覧表示

Google Cloud コンソール、Google Cloud CLI、クライアント ライブラリ、または Pub/Sub API を使用して、 Google Cloud プロジェクトのサブスクリプションを一覧表示できます。

始める前に

必要なロールと権限

サブスクリプションのリストと管理に必要な権限を取得するには、トピックまたはプロジェクトに対する 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 を使用して、 Google Cloud プロジェクトのサブスクリプションを一覧表示できます。

コンソール

プロジェクトのサブスクリプションを表示するには、[サブスクリプション] ページに移動します。

サブスクリプションに移動

サブスクリプションがページの表に一覧表示されます。

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. Google Cloud プロジェクトのサブスクリプションを一覧表示するには、gcloud pubsub subscriptions list コマンドを実行します。

    gcloud pubsub subscriptions list [--project=PROJECT_ID]

REST

プロジェクト内のサブスクリプションを一覧表示するには、projects.subscriptions.list メソッドを使用します。

リクエスト:

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

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

ここで

  • PROJECT_ID はプロジェクト ID です。

レスポンス:

{
"subscriptions": [
{
  "name": "projects/PROJECT_ID/topics/mysubscription1",
  "topic": "projects/PROJECT_ID/topics/TOPIC_ID",
  "pushConfig": {},
  "ackDeadlineSeconds": 10,
  "retainAckedMessages": true,
  "messageRetentionDuration": "604800s",
  "expirationPolicy": {}
},
{
  "name": "projects/PROJECT_ID/topics/mysubscription2",
  "topic": "projects/PROJECT_ID/topics/TOPIC_ID",
  "pushConfig": {
    "pushEndpoint": "https://PROJECT_ID.appspot.com/myhandler",
    "attributes": {
      "x-goog-version": "v1"
    }
  },
  "ackDeadlineSeconds": 10,
  "retainAckedMessages": true,
  "messageRetentionDuration": "604800s",
  "expirationPolicy": {}
}
]
}

C++

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

namespace pubsub_admin = ::google::cloud::pubsub_admin;
[](pubsub_admin::SubscriptionAdminClient client,
   std::string const& project_id) {
  int count = 0;
  google::pubsub::v1::ListSubscriptionsRequest request;
  request.set_project(google::cloud::Project(project_id).FullName());
  for (auto& subscription : client.ListSubscriptions(request)) {
    if (!subscription) throw std::move(subscription).status();
    std::cout << "Subscription Name: " << subscription->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No subscriptions found in project " << project_id << "\n";
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListSubscriptionsSample
{
    public IEnumerable<Subscription> ListSubscriptions(string projectId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        ProjectName projectName = ProjectName.FromProject(projectId);
        var subscriptions = subscriber.ListSubscriptions(projectName);
        return subscriptions;
    }
}

Go

次のサンプルでは、Go Pub/Sub クライアント ライブラリのメジャー バージョン(v2)を使用しています。引き続き v1 ライブラリを使用している場合は、v2 への移行ガイドをご覧ください。v1 コードサンプルの一覧については、 非推奨のコードサンプルをご覧ください。

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/pubsub/v2"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
	"google.golang.org/api/iterator"
)

func list(projectID string) ([]*pubsubpb.Subscription, error) {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	var subs []*pubsubpb.Subscription
	req := &pubsubpb.ListSubscriptionsRequest{
		Project: fmt.Sprintf("projects/%s", projectID),
	}
	it := client.SubscriptionAdminClient.ListSubscriptions(ctx, req)
	for {
		s, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("Next: %w", err)
		}
		subs = append(subs, s)
	}
	return subs, nil
}

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

public class ListSubscriptionsInProjectExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";

    listSubscriptionInProjectExample(projectId);
  }

  public static void listSubscriptionInProjectExample(String projectId) throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectName projectName = ProjectName.of(projectId);
      for (Subscription subscription :
          subscriptionAdminClient.listSubscriptions(projectName).iterateAll()) {
        System.out.println(subscription.getName());
      }
      System.out.println("Listed all the subscriptions in the project.");
    }
  }
}

Node.js

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

// 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 listSubscriptions() {
  // Lists all subscriptions in the current project
  const [subscriptions] = await pubSubClient.getSubscriptions();
  console.log('Subscriptions:');
  subscriptions.forEach(subscription => console.log(subscription.name));
}

Node.ts

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

// Imports the Google Cloud client library
import {PubSub, Subscription} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function listSubscriptions() {
  // Lists all subscriptions in the current project
  const [subscriptions] = await pubSubClient.getSubscriptions();
  console.log('Subscriptions:');
  subscriptions.forEach((subscription: Subscription) =>
    console.log(subscription.name),
  );
}

PHP

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

use Google\Cloud\PubSub\PubSubClient;

/**
 * Lists all Pub/Sub subscriptions.
 *
 * @param string $projectId  The Google project ID.
 */
function list_subscriptions($projectId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    foreach ($pubsub->subscriptions() as $subscription) {
        printf('Subscription: %s' . PHP_EOL, $subscription->name());
    }
}

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"

subscriber = pubsub_v1.SubscriberClient()
project_path = f"projects/{project_id}"

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    for subscription in subscriber.list_subscriptions(
        request={"project": project_path}
    ):
        print(subscription.name)

Ruby

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

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


pubsub = Google::Cloud::PubSub.new
subscription_admin = pubsub.subscription_admin

subscriptions = subscription_admin.list_subscriptions \
  project: pubsub.project_path

puts "Subscriptions:"
subscriptions.each do |subscription|
  puts subscription.name
end

トピックのサブスクリプションの一覧表示

Google Cloud コンソール、Google Cloud CLI、または Pub/Sub API を使用して、トピックにサブスクリプションを一覧表示できます。

コンソール

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

    [トピック] に移動

  2. トピック ID を選択して、[トピックの詳細] ページを開きます。ページの [サブスクリプション] セクションには、トピックのサブスクリプションの一覧が表示されます。

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. Google Cloud プロジェクトのサブスクリプションを一覧表示するには、gcloud pubsub topics list-subscriptions コマンドを実行します。

    gcloud pubsub topics list-subscriptions TOPIC_ID

REST

トピック内のサブスクリプションを一覧表示するには、projects.subscriptions.list メソッドを使用します。

リクエスト:

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

GET https://pubsub.googleapis.com/v1/projects/PROJECT_ID/topics/TOPIC_ID/subscriptions
Authorization: Bearer ACCESS_TOKEN

ここで

  • PROJECT_ID はプロジェクト ID です。
  • TOPIC_ID はトピック ID です。

レスポンス:

{
"subscriptions": [
"projects/PROJECT_ID/subscriptions/mysubscription1",
"projects/PROJECT_ID/subscriptions/mysubscription2"
]
}

C++

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

namespace pubsub_admin = ::google::cloud::pubsub_admin;
namespace pubsub = ::google::cloud::pubsub;
[](pubsub_admin::TopicAdminClient client, std::string const& project_id,
   std::string const& topic_id) {
  auto const topic = pubsub::Topic(project_id, topic_id);
  std::cout << "Subscription list for topic " << topic << ":\n";
  for (auto& name : client.ListTopicSubscriptions(topic.FullName())) {
    if (!name) throw std::move(name).status();
    std::cout << "  " << *name << "\n";
  }
}

C#

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


using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListSubscriptionsInTopicSample
{
    public IEnumerable<string> ListSubscriptionsInTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        IEnumerable<string> subscriptions = publisher.ListTopicSubscriptions(topicName);
        return subscriptions;
    }
}

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"
	"google.golang.org/api/iterator"
)

func listSubscriptions(w io.Writer, projectID, topicID string) error {
	// projectID := "my-project-id"
	// topicName := "projects/sample-248520/topics/ocr-go-test-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.ListTopicSubscriptionsRequest{
		Topic: fmt.Sprintf("projects/%s/topics/%s", projectID, topicID),
	}
	it := client.TopicAdminClient.ListTopicSubscriptions(ctx, req)
	for {
		sub, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("error listing topic subscriptions: %w", err)
		}
		fmt.Fprintf(w, "got subscription: %s\n", sub)
	}
	return nil
}

Java

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


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class ListSubscriptionsInTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    listSubscriptionInTopicExample(projectId, topicId);
  }

  public static void listSubscriptionInTopicExample(String projectId, String topicId)
      throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      for (String subscription : topicAdminClient.listTopicSubscriptions(topicName).iterateAll()) {
        System.out.println(subscription);
      }
      System.out.println("Listed all the subscriptions in the topic.");
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_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 listTopicSubscriptions(topicNameOrId) {
  // Lists all subscriptions for the topic
  const [subscriptions] = await pubSubClient
    .topic(topicNameOrId)
    .getSubscriptions();

  console.log(`Subscriptions for ${topicNameOrId}:`);
  subscriptions.forEach(subscription => console.log(subscription.name));
}

Node.ts

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';

// Imports the Google Cloud client library
import {PubSub, Subscription} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function listTopicSubscriptions(topicNameOrId: string) {
  // Lists all subscriptions for the topic
  const [subscriptions] = await pubSubClient
    .topic(topicNameOrId)
    .getSubscriptions();

  console.log(`Subscriptions for ${topicNameOrId}:`);
  subscriptions.forEach((subscription: Subscription) =>
    console.log(subscription.name),
  );
}

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)

response = publisher.list_topic_subscriptions(request={"topic": topic_path})
for subscription in response:
    print(subscription)

Ruby

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

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

# topic_id = "your-topic-id"

pubsub = Google::Cloud::PubSub.new
topic_admin = pubsub.topic_admin

response = topic_admin.list_topic_subscriptions \
  topic: pubsub.topic_path(topic_id)

puts "Subscriptions in topic #{topic_id}:"
response.subscriptions.each do |subscription_name|
  puts subscription_name
end

次のステップ

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