Mencantumkan topik

Dokumen ini menjelaskan cara mencantumkan topik Pub/Sub. Untuk mencantumkan a topik, Anda dapat menggunakan Cloud de Confiance konsol, gcloud CLI, library klien, atau Pub/Sub API.

Sebelum memulai

Peran dan izin yang diperlukan

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

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

Izin yang diperlukan

Izin berikut diperlukan untuk mencantumkan topik dan mengelolanya:

  • Membuat topik: pubsub.topics.create
  • Menghapus topik: pubsub.topics.delete
  • Melepaskan langganan dari topik: pubsub.topics.detachSubscription
  • Mendapatkan topik: pubsub.topics.get
  • Mencantumkan topik: pubsub.topics.list
  • Memublikasikan ke topik: pubsub.topics.publish
  • Mengupdate topik: pubsub.topics.update
  • Mendapatkan kebijakan IAM untuk topik: pubsub.topics.getIamPolicy
  • Mengonfigurasi kebijakan IAM untuk topik: pubsub.topics.setIamPolicy

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

Anda dapat mengonfigurasi kontrol akses di tingkat project dan di tingkat resource individual. Anda dapat membuat langganan di satu project dan melampirkannya ke topik yang berada di project lain. Pastikan Anda memiliki izin yang diperlukan untuk setiap project.

Mencantumkan topik

Konsol

  • Di Cloud de Confiance konsol, buka halaman Pub/Sub Topics.

  • Buka Topik

    Halaman Topics mencantumkan semua topik yang tersedia.

    Secara default, konsol menampilkan 50 topik. Anda dapat meningkatkan nilai ini untuk menampilkan maksimum 200 topik menggunakan tombol drop-down Rows per page. Tombol ini hanya muncul di konsol jika Anda memiliki lebih dari 20 topik dalam project.

gcloud

  1. Di konsol, aktifkan Cloud Shell. Cloud de Confiance

    Aktifkan Cloud Shell

    Di bagian bawah konsol Cloud de Confiance , sesi Cloud Shell akan dimulai dan menampilkan prompt command line. Cloud Shell adalah lingkungan shell dengan Google Cloud CLI yang sudah terinstal, dan dengan nilai yang sudah ditetapkan untuk project Anda saat ini. Diperlukan waktu beberapa detik untuk melakukan inisialisasi pada sesi.

  2. Untuk mencantumkan topik, gunakan gcloud pubsub topics list perintah:

    gcloud pubsub topics list

Secara default, maksimum 100 hasil ditampilkan per kueri. Anda dapat menentukan nilai alternatif hingga 1.000 menggunakan parameter ukuran halaman. Misalnya, menggunakan Google Cloud CLI, tentukan --page-size=1000.

REST

Untuk mencantumkan topik, gunakan projects.topics.list metode:

Permintaan:

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

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

Dengan:

  • PROJECT_ID adalah project ID Anda.
  • Respons:

    {
    "topics": [
      {
        "name": "projects/PROJECT_ID/topics/mytopic1",
        ...
      },
      {
        "name": "projects/PROJECT_ID/topics/mytopic2",
        ...
      }
    ]
    }

    C++

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

    namespace pubsub_admin = ::google::cloud::pubsub_admin;
    [](pubsub_admin::TopicAdminClient client, std::string const& project_id) {
      int count = 0;
      for (auto& topic : client.ListTopics("projects/" + project_id)) {
        if (!topic) throw std::move(topic).status();
        std::cout << "Topic Name: " << topic->name() << "\n";
        ++count;
      }
      if (count == 0) {
        std::cout << "No topics 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 C# API Pub/Sub.

    
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.PubSub.V1;
    using System.Collections.Generic;
    
    public class ListProjectTopicsSample
    {
        public IEnumerable<Topic> ListProjectTopics(string projectId)
        {
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            ProjectName projectName = ProjectName.FromProject(projectId);
            IEnumerable<Topic> topics = publisher.ListTopics(projectName);
            return topics;
        }
    }

    Go

    Contoh berikut menggunakan library klien Pub/Sub Go 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 Go API Pub/Sub.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/pubsub/v2"
    	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
    	"google.golang.org/api/iterator"
    )
    
    func listTopics(w io.Writer, projectID string) error {
    	// projectID := "my-project-id"
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &pubsubpb.ListTopicsRequest{
    		Project: fmt.Sprintf("projects/%s", projectID),
    	}
    	it := client.TopicAdminClient.ListTopics(ctx, req)
    	for {
    		topic, err := it.Next()
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return fmt.Errorf("error listing topics: %w", err)
    		}
    		fmt.Fprintf(w, "got topic: %s\n", topic)
    
    	}
    	return nil
    }
    

    Java

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

    
    import com.google.cloud.pubsub.v1.TopicAdminClient;
    import com.google.pubsub.v1.ProjectName;
    import com.google.pubsub.v1.Topic;
    import java.io.IOException;
    
    public class ListTopicsExample {
      public static void main(String... args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
    
        listTopicsExample(projectId);
      }
    
      public static void listTopicsExample(String projectId) throws IOException {
        try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
          ProjectName projectName = ProjectName.of(projectId);
          for (Topic topic : topicAdminClient.listTopics(projectName).iterateAll()) {
            System.out.println(topic.getName());
          }
          System.out.println("Listed all topics.");
        }
      }
    }

    Node.js

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Node.js API 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 listAllTopics() {
      // Lists all topics in the current project
      const [topics] = await pubSubClient.getTopics();
      console.log('Topics:');
      topics.forEach(topic => console.log(topic.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 Node.js API Pub/Sub.

    // Imports the Google Cloud client library
    import {PubSub, Topic} from '@google-cloud/pubsub';
    
    // Creates a client; cache this for further use
    const pubSubClient = new PubSub();
    
    async function listAllTopics() {
      // Lists all topics in the current project
      const [topics] = await pubSubClient.getTopics();
      console.log('Topics:');
      topics.forEach((topic: Topic) => console.log(topic.name));
    }

    PHP

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

    use Google\Cloud\PubSub\PubSubClient;
    
    /**
     * Lists all Pub/Sub topics.
     *
     * @param string $projectId  The Google project ID.
     */
    function list_topics($projectId)
    {
        $pubsub = new PubSubClient([
            'projectId' => $projectId,
        ]);
        foreach ($pubsub->topics() as $topic) {
            printf('Topic: %s' . PHP_EOL, $topic->name());
        }
    }

    Python

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

    from google.cloud import pubsub_v1
    
    # TODO(developer)
    # project_id = "your-project-id"
    
    publisher = pubsub_v1.PublisherClient()
    project_path = f"projects/{project_id}"
    
    for topic in publisher.list_topics(request={"project": project_path}):
        print(topic)

    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 Ruby API Pub/Sub.

    
    pubsub = Google::Cloud::PubSub.new
    topic_admin = pubsub.topic_admin
    
    topics = topic_admin.list_topics project: pubsub.project_path
    
    puts "Topics in project:"
    topics.each do |topic|
      puts topic.name
    end

    Langkah berikutnya