Hapus topik

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

Sebelum memulai

Peran dan izin yang diperlukan

Untuk mendapatkan izin yang diperlukan guna menghapus topik dan mengelolanya, minta administrator untuk memberi Anda peran IAM Editor Pub/Sub(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 topik dan mengelolanya. Untuk melihat izin yang benar-benar diperlukan, perluas bagian Izin yang diperlukan:

Izin yang diperlukan

Izin berikut diperlukan untuk menghapus 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.

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 topik yang baru saja dihapus, akan terjadi error dalam waktu singkat.

Konsol

  1. Di Google Cloud konsol, 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. Di konsol, aktifkan Cloud Shell. Google Cloud

    Aktifkan Cloud Shell

    Di bagian bawah konsol Google Cloud , 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 menghapus topik, gunakan gcloud pubsub topics delete perintah:

    gcloud pubsub topics delete TOPIC_ID

REST

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

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:

  • 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 C++ API Pub/Sub.

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 C# API 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 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"
)

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


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 Node.js API 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 Node.js API 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 PHP API 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 Python API 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)

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 Ruby API 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