列出订阅

您可以使用 Google Cloud 控制台、Google Cloud CLI、客户端库或 Pub/Sub API。

准备工作

所需的角色和权限

如需获得列出订阅和管理订阅所需的权限,请让您的管理员为您授予主题或项目的 Pub/Sub Editor (roles/pubsub.editor) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

此预定义角色包含列出订阅和管理订阅所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

如需列出订阅并进行管理,您需要具备以下权限:

  • 从订阅中拉取: 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。

控制台

要列出项目中的订阅,请转到订阅页面。

前往“订阅”页面

您订阅的频道会列在该页面上的表格中。

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 快速入门: 客户端库。 有关详情,请参阅 Pub/Sub C++ API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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 快速入门: 客户端库。 如需了解详情,请参阅 Pub/Sub C# API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    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 快速入门: 客户端库。 有关详情,请参阅 Pub/Sub Go API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    import (
    	"context"
    	"fmt"
    
    	"cloud.google.com/go/pubsub"
    	"google.golang.org/api/iterator"
    )
    
    func list(projectID string) ([]*pubsub.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 []*pubsub.Subscription
    	it := client.Subscriptions(ctx)
    	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 快速入门: 客户端库。 有关详情,请参阅 Pub/Sub Java API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    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

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

    // 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 快速入门: 客户端库。 有关详情,请参阅 Pub/Sub PHP API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    pubsub = Google::Cloud::Pubsub.new
    
    subscriptions = pubsub.list_subscriptions
    
    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++

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C++ 设置说明进行操作。 有关详情,请参阅 Pub/Sub C++ API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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 快速入门: 客户端库。 有关详情,请参阅 Pub/Sub C# API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    import (
    	"context"
    	"fmt"
    
    	"cloud.google.com/go/pubsub"
    	"google.golang.org/api/iterator"
    )
    
    func listSubscriptions(projectID, topicID string) ([]*pubsub.Subscription, 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 nil, fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	var subs []*pubsub.Subscription
    
    	it := client.Topic(topicID).Subscriptions(ctx)
    	for {
    		sub, err := it.Next()
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return nil, fmt.Errorf("Next: %w", err)
    		}
    		subs = append(subs, sub)
    	}
    	return subs, nil
    }
    

    Java

    在尝试此示例之前,请按照Java Pub/Sub 快速入门: 客户端库。 有关详情,请参阅 Pub/Sub Java API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    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

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

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

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    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 快速入门: 客户端库。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    # topic_id = "your-topic-id"
    
    pubsub = Google::Cloud::Pubsub.new
    
    topic         = pubsub.topic topic_id
    subscriptions = topic.subscriptions
    
    puts "Subscriptions in topic #{topic.name}:"
    subscriptions.each do |subscription|
      puts subscription.name
    end

    后续步骤