הצגת רשימה של מינויים

אפשר להציג את רשימת המינויים בפרויקט ב- Google Cloud באמצעות מסוףGoogle Cloud , ‏Google Cloud CLI, ספריית הלקוח או Pub/Sub API.

לפני שמתחילים

תפקידים והרשאות נדרשים

כדי לקבל את ההרשאות שנדרשות להצגת רשימת המינויים, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד עריכה ב-Pub/Sub (roles/pubsub.editor) בפרויקט. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

זהו תפקיד שמוגדר מראש וכולל את ההרשאות שנדרשות כדי להציג רשימת מינויים. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי להציג רשימה של מינויים, נדרשות ההרשאות הבאות:

  • הצגת רשימה של מינויים בפרויקט: pubsub.subscriptions.list בפרויקט
  • הצגת רשימת המינויים לנושא: pubsub.topics.get בנושא

יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.

הצגת רשימה של המינויים בפרויקט

אפשר להציג את רשימת המינויים בפרויקט ב- Google Cloud באמצעות מסוףGoogle Cloud , ‏Google Cloud CLI, ספריית הלקוח או Pub/Sub API.

המסוף

כדי להציג את רשימת המינויים בפרויקט, נכנסים לדף Subscriptions.

אל הדף "מינויים"

המינויים שלכם מופיעים בטבלה שבדף.

gcloud

  1. מפעילים את Cloud Shell במסוף Google Cloud .

    הפעלת Cloud Shell

    בחלק התחתון של מסוף Google Cloud יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  2. כדי להציג את רשימת המינויים בפרויקט ב- Google Cloud , מריצים את הפקודה gcloud pubsub subscriptions list:

    gcloud pubsub subscriptions list [--project=PROJECT_ID]

    כברירת מחדל, הפקודה הזו מחזירה עד 100 תוצאות לכל שאילתה. כדי לקבל יותר תוצאות, משתמשים בדגל --page-size:

    gcloud pubsub subscriptions list --page-size=PAGE_SIZE

    מחליפים את PAGE_SIZE במספר המקסימלי של תוצאות שרוצים לקבל. הערך לא יכול להיות גבוה מ-1,000.

REST

כדי להציג רשימה של מינויים בפרויקט, משתמשים ב-method‏ projects.subscriptions.list:

בקשה:

הבקשה צריכה לעבור אימות באמצעות אסימון גישה בכותרת Authorization. כדי לקבל אסימון גישה ל-Application Default Credentials הנוכחי: gcloud auth application-default print-access-token.

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

כאשר:

  • ‫PROJECT_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;
    }
}

המשך

בדוגמה הבאה נעשה שימוש בגרסה הראשית של ספריית הלקוח של Pub/Sub ב-Go (גרסה 2). אם אתם עדיין משתמשים בספרייה של גרסה 1, עיינו במדריך להעברת נתונים לגרסה 2. דוגמאות קוד שהוצאו משימוש

לפני שתנסו את הדוגמה הזו, פעלו לפי הוראות ההגדרה של Go במאמר מדריך למתחילים: שימוש בספריות לקוח. מידע נוסף מופיע במסמכי העזר של ה-API של Pub/Sub Go.

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 במאמר מדריך למתחילים: שימוש בספריות לקוח. מידע נוסף מופיע במאמרי העזרה של ה-API בשפת Python של 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

בדוגמה הבאה נעשה שימוש בגרסה 3 של ספריית הלקוח של Pub/Sub ב-Ruby. אם אתם עדיין משתמשים בספרייה 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

Rust

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Rust במדריך למתחילים: שימוש בספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Pub/Sub Rust API.

use google_cloud_gax::paginator::ItemPaginator;
use google_cloud_pubsub::client::SubscriptionAdmin;

pub async fn sample(client: &SubscriptionAdmin, project: &str) -> anyhow::Result<()> {
    let mut subscriptions = client
        .list_subscriptions()
        .set_project(format!("projects/{}", project))
        .by_item();

    println!("listing subscriptions");
    while let Some(subscription) = subscriptions.next().await.transpose()? {
        println!("{subscription:?}");
    }
    println!("DONE");
    Ok(())
}

הצגת רשימת המינויים לנושא

אפשר להציג את רשימת המינויים לנושא באמצעות מסוף Google Cloud , Google Cloud CLI או Pub/Sub API.

המסוף

  1. נכנסים לדף Topics במסוף Google Cloud .

    מעבר אל "נושאים"

  2. בוחרים מזהה נושא כדי לפתוח את הדף פרטי הנושא. בקטע Subscriptions בדף מופיעה רשימה של מינויים לנושא.

gcloud

  1. מפעילים את Cloud Shell במסוף Google Cloud .

    הפעלת Cloud Shell

    בחלק התחתון של מסוף Google Cloud יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  2. כדי להציג את רשימת המינויים בפרויקט ב- Google Cloud , מריצים את הפקודה gcloud pubsub topics list-subscriptions:

    gcloud pubsub topics list-subscriptions TOPIC_ID
  3. כברירת מחדל, הפקודה הזו מחזירה עד 100 תוצאות לכל שאילתה. כדי לקבל יותר תוצאות, משתמשים בדגל --page-size:

    gcloud pubsub subscriptions list --page-size=PAGE_SIZE

    מחליפים את PAGE_SIZE במספר המקסימלי של תוצאות שרוצים לקבל. הערך לא יכול להיות גבוה מ-1,000.

REST

כדי להציג את המינויים לנושא, משתמשים ב-method‏ projects.subscriptions.list:

בקשה:

הבקשה צריכה לעבור אימות באמצעות אסימון גישה בכותרת Authorization. כדי לקבל אסימון גישה ל-Application Default Credentials הנוכחי: 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 הוא מזהה הפרויקט.
  • ‫TOPIC_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;
    }
}

המשך

בדוגמה הבאה נעשה שימוש בגרסה הראשית של ספריית הלקוח של Pub/Sub ב-Go (גרסה 2). אם אתם עדיין משתמשים בספרייה של גרסה 1, עיינו במדריך להעברת נתונים לגרסה 2. דוגמאות קוד שהוצאו משימוש

לפני שתנסו את הדוגמה הזו, פעלו לפי הוראות ההגדרה של Go במאמר מדריך למתחילים: שימוש בספריות לקוח. מידע נוסף מופיע במסמכי העזר של ה-API של Pub/Sub Go.

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 במאמר מדריך למתחילים: שימוש בספריות לקוח. מידע נוסף מופיע במאמרי העזרה של ה-API בשפת Python של 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

בדוגמה הבאה נעשה שימוש בגרסה 3 של ספריית הלקוח של Pub/Sub ב-Ruby. אם אתם עדיין משתמשים בספרייה 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

Rust

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Rust במדריך למתחילים: שימוש בספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Pub/Sub Rust API.

use google_cloud_gax::paginator::ItemPaginator;
use google_cloud_pubsub::client::TopicAdmin;

pub async fn sample(client: &TopicAdmin, project_id: &str, topic_id: &str) -> anyhow::Result<()> {
    let mut subscriptions = client
        .list_topic_subscriptions()
        .set_topic(format!("projects/{project_id}/topics/{topic_id}"))
        .by_item();

    println!("listing topic subscriptions");
    while let Some(subscription) = subscriptions.next().await.transpose()? {
        println!("{subscription:?}");
    }
    println!("DONE");
    Ok(())
}

המאמרים הבאים