Hapus langganan

Anda dapat menghapus langganan Pub/Sub dengan konsol Google Cloud , Google Cloud CLI, library klien, atau Pub/Sub API.

Dokumen ini membahas cara menghapus langganan di Pub/Sub.

Sebelum memulai

Peran dan izin yang diperlukan

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

Peran bawaan ini berisi izin pubsub.subscriptions.delete, yang diperlukan untuk menghapus langganan.

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

Hapus langganan

Konsol

  1. Di konsol Google Cloud , buka halaman Subscriptions.

    Buka Langganan

  2. Pilih langganan yang akan dihapus.
  3. Klik Hapus.

gcloud

  1. Di konsol Google Cloud , aktifkan Cloud Shell.

    Aktifkan Cloud Shell

    Di bagian bawah konsol Google Cloud , sesi Cloud Shell akan dimulai 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 pada sesi.

  2. Untuk menghapus langganan, jalankan perintah gcloud pubsub subscriptions delete:

    gcloud pubsub subscriptions delete SUBSCRIPTION_ID

REST

Untuk menghapus langganan, gunakan metode projects.subscriptions.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/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer ACCESS_TOKEN

Dengan:

  • PROJECT_ID adalah project ID Anda.
  • SUBSCRIPTION_ID adalah ID langganan Anda.

Respons:

Jika permintaan berhasil, responsnya adalah objek JSON kosong.

Penghapusan adalah operasi yang pada akhirnya konsisten, sehingga mungkin perlu waktu agar proses lain melihat efeknya.

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.

namespace pubsub_admin = ::google::cloud::pubsub_admin;
namespace pubsub = ::google::cloud::pubsub;
[](pubsub_admin::SubscriptionAdminClient client,
   std::string const& project_id, std::string const& subscription_id) {
  auto status = client.DeleteSubscription(
      pubsub::Subscription(project_id, subscription_id).FullName());
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The subscription was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The subscription 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 DeleteSubscriptionSample
{
    public void DeleteSubscription(string projectId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        subscriber.DeleteSubscription(subscriptionName);
    }
}

Go

Contoh berikut menggunakan versi utama library klien Go Pub/Sub (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 API Go 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, subID string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.DeleteSubscriptionRequest{
		Subscription: fmt.Sprintf("projects/%s/subscriptions/%s", projectID, subID),
	}
	if err := client.SubscriptionAdminClient.DeleteSubscription(ctx, req); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}
	fmt.Fprintf(w, "Subscription %q deleted.", subID)
	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.SubscriptionAdminClient;
import com.google.pubsub.v1.SubscriptionName;
import java.io.IOException;

public class DeleteSubscriptionExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    deleteSubscriptionExample(projectId, subscriptionId);
  }

  public static void deleteSubscriptionExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
      try {
        subscriptionAdminClient.deleteSubscription(subscriptionName);
        System.out.println("Deleted subscription.");
      } 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 subscriptionNameOrId = 'YOUR_SUBSCRIPTION_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 deleteSubscription(subscriptionNameOrId) {
  // Deletes the subscription
  await pubSubClient.subscription(subscriptionNameOrId).delete();
  console.log(`Subscription ${subscriptionNameOrId} 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 subscriptionNameOrId = 'YOUR_SUBSCRIPTION_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 deleteSubscription(subscriptionNameOrId: string) {
  // Deletes the subscription
  await pubSubClient.subscription(subscriptionNameOrId).delete();
  console.log(`Subscription ${subscriptionNameOrId} 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 subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function delete_subscription($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $subscription->delete();

    printf('Subscription deleted: %s' . PHP_EOL, $subscription->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"
# subscription_id = "your-subscription-id"

subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(project_id, subscription_id)

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    subscriber.delete_subscription(request={"subscription": subscription_path})

print(f"Subscription deleted: {subscription_path}.")

Ruby

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

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::PubSub.new
subscription_admin = pubsub.subscription_admin

subscription_admin.delete_subscription \
  subscription: pubsub.subscription_path(subscription_id)

puts "Subscription #{subscription_id} deleted."

Anda dapat membuat langganan dengan nama yang sama seperti langganan yang baru saja Anda hapus. Namun, langganan yang baru dibuat sepenuhnya terpisah dari langganan yang dihapus sebelumnya. Pesan yang ditujukan untuk langganan lama tidak akan dikirim ke langganan baru.

Langkah berikutnya

  • Buat atau ubah langganan dengan perintah gcloud.
  • Buat atau ubah langganan dengan REST API.