Mencantumkan langganan

Anda dapat mencantumkan langganan dalam Trusted Cloud project dengan Trusted Cloud konsol, Google Cloud CLI, library klien, atau Pub/Sub API.

Sebelum memulai

Peran dan izin yang diperlukan

Untuk mendapatkan izin yang diperlukan untuk mencantumkan dan mengelola langganan, minta administrator untuk memberi Anda peran IAM Pub/Sub Editor (roles/pubsub.editor) di topik atau project Anda. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Peran bawaan ini berisi izin yang diperlukan untuk mencantumkan langganan dan mengelolanya. Untuk melihat izin yang benar-benar diperlukan, luaskan bagian Izin yang diperlukan:

Izin yang diperlukan

Izin berikut diperlukan untuk mencantumkan langganan dan mengelolanya:

  • Menarik dari langganan: pubsub.subscriptions.consume
  • Buat langganan: pubsub.subscriptions.create
  • Menghapus langganan: pubsub.subscriptions.delete
  • Mendapatkan langganan: pubsub.subscriptions.get
  • Mencantumkan langganan: pubsub.subscriptions.list
  • Memperbarui langganan: pubsub.subscriptions.update
  • Melampirkan langganan ke topik: pubsub.topics.attachSubscription
  • Dapatkan kebijakan IAM untuk langganan: pubsub.subscriptions.getIamPolicy
  • Konfigurasi kebijakan IAM untuk langganan: pubsub.subscriptions.setIamPolicy

Anda mungkin juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaan lainnya.

Mencantumkan langganan

Anda dapat mencantumkan langganan dalam Trusted Cloud project dengan Trusted Cloud konsol, Google Cloud CLI, library klien, atau Pub/Sub API.

Konsol

Untuk mencantumkan langganan dalam project, buka halaman Subscriptions.

Buka Langganan

Subscription Anda tercantum dalam tabel di halaman.

gcloud

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted 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. Untuk mencantumkan langganan dalam project Trusted Cloud , jalankan perintah gcloud pubsub subscriptions list:

    gcloud pubsub subscriptions list [--project=PROJECT_ID]
  3. REST

    Untuk mencantumkan langganan dalam project, gunakan metode projects.subscriptions.list:

    Permintaan:

    Permintaan harus diautentikasi dengan token akses di header Authorization. Untuk mendapatkan token akses bagi Kredensial Default Aplikasi saat ini: gcloud auth application-default print-access-token.

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

    Dengan:

    • PROJECT_ID adalah project ID Anda.

    Respons:

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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C++ di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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#

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# 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

    Contoh berikut menggunakan library klien Go Pub/Sub versi utama (v2). Jika Anda masih menggunakan library v1, lihat panduan migrasi ke v2. Untuk melihat daftar contoh kode v1, lihat contoh kode yang tidak digunakan lagi.

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan PHP di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API PHP 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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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

    Contoh berikut menggunakan library klien Pub/Sub Ruby v3. Jika Anda masih menggunakan library v2, lihat panduan migrasi ke v3. Untuk melihat daftar contoh kode Ruby v2, lihat contoh kode yang tidak digunakan lagi.

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Pub/Sub.

    
    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

Mencantumkan langganan ke topik

Anda dapat mencantumkan langganan ke topik dengan Trusted Cloud konsol, Google Cloud CLI, atau Pub/Sub API.

Konsol

  1. Di konsol Trusted Cloud , buka halaman Topics.

    Buka Topik

  2. Pilih ID topik untuk membuka halaman Detail topik. Bagian Subscriptions di halaman ini berisi daftar langganan ke topik.

gcloud

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted 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. Untuk mencantumkan langganan dalam project Trusted Cloud , jalankan perintah gcloud pubsub topics list-subscriptions:

    gcloud pubsub topics list-subscriptions TOPIC_ID
  3. REST

    Untuk mencantumkan langganan dalam topik, gunakan metode projects.subscriptions.list:

    Permintaan:

    Permintaan harus diautentikasi dengan token akses di header Authorization. Untuk mendapatkan token akses bagi Kredensial Default Aplikasi saat ini: gcloud auth application-default print-access-token.

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

    Dengan:

    • PROJECT_ID adalah project ID Anda.
    • TOPIC_ID adalah topic ID Anda.

    Respons:

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

    C++

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C++ di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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#

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# 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

    Contoh berikut menggunakan library klien Go Pub/Sub versi utama (v2). Jika Anda masih menggunakan library v1, lihat panduan migrasi ke v2. Untuk melihat daftar contoh kode v1, lihat contoh kode yang tidak digunakan lagi.

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi 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

    Contoh berikut menggunakan library klien Pub/Sub Ruby v3. Jika Anda masih menggunakan library v2, lihat panduan migrasi ke v3. Untuk melihat daftar contoh kode Ruby v2, lihat contoh kode yang tidak digunakan lagi.

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Pub/Sub.

    # 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

Langkah berikutnya

  • Buat atau ubah langganan dengan perintah gcloud.
  • Buat atau ubah langganan dengan REST API.