Menghapus topik

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

Sebelum memulai

Peran dan izin yang diperlukan

Untuk mendapatkan izin yang diperlukan untuk menghapus topik dan mengelolanya, minta administrator untuk memberi Anda peran IAM Pub/Sub Editor(roles/pubsub.editor) pada topik atau project Anda. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses.

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

Izin yang diperlukan

Izin berikut diperlukan untuk menghapus dan mengelolanya:

  • Buat topik: pubsub.topics.create
  • Menghapus topik: pubsub.topics.delete
  • Melepas langganan dari topik: pubsub.topics.detachSubscription
  • Dapatkan topik: pubsub.topics.get
  • Buat daftar topik: pubsub.topics.list
  • Memublikasikan ke topik: pubsub.topics.publish
  • Perbarui topik: pubsub.topics.update
  • Dapatkan kebijakan IAM untuk topik: pubsub.topics.getIamPolicy
  • Konfigurasi kebijakan IAM untuk topik: pubsub.topics.setIamPolicy

Anda mung juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaanlainnya.

Anda dapat mengonfigurasi kontrol akses pada level project dan level resource individual. Anda dapat membuat langganan dalam satu project dan melampirkannya ke topik yang terletak di project berbeda. 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 akan memiliki nama topik _deleted-topic_. Jika Anda mencoba membuat topik dengan nama yang sama dengan yang baru saja dihapus, akan terjadi error untuk sementara waktu.

Konsol

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

  2. Buka Topik

  3. Pilih topik, lalu klik Tindakan lainnya.

  4. Klik Delete.

    Jendela Delete topic akan muncul.

  5. Masukkan delete, lalu klik Delete.

gcloud

  1. Di konsol Google Cloud, aktifkan Cloud Shell.

    Aktifkan Cloud Shell

    Di bagian bawah Google Cloud Console, Cloud Shell sesi akan terbuka dan menampilkan perintah 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 sesi.

  2. Untuk menghapus topik, gunakan perintah gcloud pubsub topics delete:

    gcloud pubsub topics delete TOPIC_ID

REST

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

Permintaan:

Permintaan harus diautentikasi dengan token akses di header Authorization. Untuk mendapatkan token akses untuk 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 keterangan:

  • 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 Pub/Sub menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API C++ Pub/Sub.

    Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    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 Pub/Sub menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API C# Pub/Sub.

    Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    
    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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di panduan memulai Pub/Sub menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Go Pub/Sub.

    Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/pubsub"
    )
    
    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()
    
    	t := client.Topic(topicID)
    	if err := t.Delete(ctx); err != nil {
    		return fmt.Errorf("Delete: %w", err)
    	}
    	fmt.Fprintf(w, "Deleted topic: %v\n", t)
    	return nil
    }
    

    Java

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di panduan memulai Pub/Sub menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Java Pub/Sub.

    Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    
    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

    /**
     * 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.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} 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 Pub/Sub menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API PHP Pub/Sub.

    Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    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 Pub/Sub menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Python Pub/Sub.

    Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby di panduan memulai Pub/Sub menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Ruby Pub/Sub.

    Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    # topic_id = "your-topic-id"
    
    pubsub = Google::Cloud::Pubsub.new
    
    topic = pubsub.topic topic_id
    topic.delete
    
    puts "Topic #{topic_id} deleted."

    Langkah selanjutnya