Hapus topik

Dokumen ini menjelaskan cara menghapus topik Pub/Sub. Untuk menghapus topik, Anda dapat menggunakan konsol Trusted Cloud , Google CLI, library klien, atau Pub/Sub API.

Sebelum memulai

Peran dan izin yang diperlukan

Untuk mendapatkan izin yang diperlukan guna menghapus dan mengelola topik, minta administrator Anda 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 menghapus dan mengelola topik. Untuk melihat izin yang benar-benar diperlukan, luaskan bagian Izin yang diperlukan:

Izin yang diperlukan

Izin berikut diperlukan untuk menghapus dan mengelola topik:

  • Buat 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
  • Memperbarui topik: pubsub.topics.update
  • Dapatkan kebijakan IAM untuk topik: pubsub.topics.getIamPolicy
  • Konfigurasi 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 dalam satu project dan melampirkannya ke topik yang berada dalam project lain. Pastikan Anda memiliki izin yang diperlukan untuk setiap project.

Menghapus topik

Saat Anda menghapus topik, langganannya tidak akan dihapus. Backlog pesan dari langganan tersedia untuk pelanggan. Setelah topik dihapus, langganannya memiliki nama topik _deleted-topic_. Jika Anda mencoba membuat topik dengan nama yang sama dengan topik yang baru saja Anda hapus, akan terjadi error selama beberapa saat.

Konsol

  1. Di konsol Trusted Cloud , buka halaman Topics Pub/Sub.

  2. Buka Topik

  3. Pilih topik, lalu klik Tindakan lainnya.

  4. Klik Hapus.

    Jendela Hapus topik akan muncul.

  5. Masukkan delete, lalu klik Hapus.

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 menghapus topik, gunakan perintah gcloud pubsub topics delete:

    gcloud pubsub topics delete TOPIC_ID
  3. REST

    Untuk menghapus topik, gunakan metode projects.topics.delete:

    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.

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

    Dengan:

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

    Respons:

    Jika permintaan berhasil, responsnya adalah objek JSON kosong.

    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 = ::google::cloud::pubsub;
    namespace pubsub_admin = ::google::cloud::pubsub_admin;
    [](pubsub_admin::TopicAdminClient client, std::string const& project_id,
       std::string const& topic_id) {
      auto status =
          client.DeleteTopic(pubsub::Topic(project_id, topic_id).FullName());
      // Note that kNotFound is a possible result when the library retries.
      if (status.code() == google::cloud::StatusCode::kNotFound) {
        std::cout << "The topic was not found\n";
        return;
      }
      if (!status.ok()) throw std::runtime_error(status.message());
    
      std::cout << "The topic was successfully deleted\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;
    
    public class DeleteTopicSample
    {
        public void DeleteTopic(string projectId, string topicId)
        {
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
            publisher.DeleteTopic(topicName);
        }
    }

    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"
    )
    
    func delete(w io.Writer, projectID, topicID string) error {
    	// projectID := "my-project-id"
    	// topicID := "my-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.DeleteTopicRequest{
    		Topic: fmt.Sprintf("projects/%s/topics/%s", projectID, topicID),
    	}
    	err = client.TopicAdminClient.DeleteTopic(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to delete topic: %w", err)
    	}
    	fmt.Fprintln(w, "Deleted 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 Pub/Sub Java API.

    
    import com.google.api.gax.rpc.NotFoundException;
    import com.google.cloud.pubsub.v1.TopicAdminClient;
    import com.google.pubsub.v1.TopicName;
    import java.io.IOException;
    
    public class DeleteTopicExample {
      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";
    
        deleteTopicExample(projectId, topicId);
      }
    
      public static void deleteTopicExample(String projectId, String topicId) throws IOException {
        try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
          TopicName topicName = TopicName.of(projectId, topicId);
          try {
            topicAdminClient.deleteTopic(topicName);
            System.out.println("Deleted topic.");
          } catch (NotFoundException e) {
            System.out.println(e.getMessage());
          }
        }
      }
    }

    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 deleteTopic(topicNameOrId) {
      /**
       * TODO(developer): Uncomment the following line to run the sample.
       */
      // const topicName = 'my-topic';
    
      // Deletes the topic
      await pubSubClient.topic(topicNameOrId).delete();
      console.log(`Topic ${topicNameOrId} deleted.`);
    }

    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} from '@google-cloud/pubsub';
    
    // Creates a client; cache this for further use
    const pubSubClient = new PubSub();
    
    async function deleteTopic(topicNameOrId: string) {
      /**
       * TODO(developer): Uncomment the following line to run the sample.
       */
      // const topicName = 'my-topic';
    
      // Deletes the topic
      await pubSubClient.topic(topicNameOrId).delete();
      console.log(`Topic ${topicNameOrId} deleted.`);
    }

    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;
    
    /**
     * Creates a Pub/Sub topic.
     *
     * @param string $projectId  The Google project ID.
     * @param string $topicName  The Pub/Sub topic name.
     */
    function delete_topic($projectId, $topicName)
    {
        $pubsub = new PubSubClient([
            'projectId' => $projectId,
        ]);
        $topic = $pubsub->topic($topicName);
        $topic->delete();
    
        printf('Topic deleted: %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 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)
    
    publisher.delete_topic(request={"topic": topic_path})
    
    print(f"Topic deleted: {topic_path}")

    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
    
    topic_admin.delete_topic topic: pubsub.topic_path(topic_id)
    
    puts "Topic #{topic_id} deleted."

Langkah berikutnya