Melepaskan langganan

Saat membuat langganan, Anda melampirkan langganan ke topik, dan pelanggan dapat menerima pesan dari langganan tersebut. Untuk menghentikan pelanggan menerima pesan, Anda dapat melepaskan langganan dari topik.

Sebelum memisahkan langganan, Anda memerlukan izin pubsub.topics.detachSubscription pada topik. Anda dapat melepaskan langganan tanpa izin pada langganan, yang berguna untuk mengelola topik yang berada dalam project yang berbeda dengan langganan. Untuk mengetahui informasi selengkapnya, lihat Kontrol akses Pub/Sub.

Sebelum memulai

Peran dan izin yang diperlukan

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

Izin yang diperlukan

Izin berikut diperlukan untuk melepaskan langganan dan mengelolanya:

  • Menarik dari langganan: pubsub.subscriptions.consume
  • Buat langganan: pubsub.subscriptions.create
  • Menghapus langganan: pubsub.subscriptions.delete
  • Mendapatkan langganan: pubsub.subscriptions.get
  • Mencantumkan langganan: pubsub.subscriptions.list
  • Memperbarui langganan: pubsub.subscriptions.update
  • Melampirkan langganan ke topik: pubsub.topics.attachSubscription
  • Dapatkan kebijakan IAM untuk langganan: pubsub.subscriptions.getIamPolicy
  • Konfigurasi kebijakan IAM untuk langganan: pubsub.subscriptions.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.

Melepaskan langganan dari topik

Anda dapat melepaskan langganan dari topik menggunakan konsol Trusted Cloud , Google Cloud CLI, library klien, atau Pub/Sub API.

Konsol

Untuk melepaskan langganan, ikuti langkah-langkah berikut:

  1. Di konsol Trusted Cloud , buka halaman Topics.

    Buka Topik

  2. Pilih topik yang langganannya ingin Anda batalkan.

  3. Di tab Langganan, pilih langganan yang akan dilepas.

  4. Di halaman Subscription details, klik Detach.

  5. Pada dialog yang muncul, klik Lepaskan lagi.

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 melepaskan langganan, gunakan perintah gcloud pubsub topics detach-subscription:

    gcloud pubsub topics detach-subscription SUBSCRIPTION_ID

    Jika permintaan berhasil, command line akan menampilkan konfirmasi:

    Detached subscription [SUBSCRIPTION_ID].
  3. REST

    Untuk melepaskan langganan, gunakan metode projects.subscriptions.detach.

    Permintaan:

    Permintaan harus diautentikasi dengan token akses di header Authorization. Untuk mendapatkan token akses bagi Kredensial Default Aplikasi saat ini, gunakan perintah gcloud auth application-default print-access-token.

    POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:detach
    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.

    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& subscription_id) {
      google::pubsub::v1::DetachSubscriptionRequest request;
      request.set_subscription(
          pubsub::Subscription(project_id, subscription_id).FullName());
      auto response = client.DetachSubscription(request);
      if (!response.ok()) throw std::move(response).status();
    
      std::cout << "The subscription was successfully detached: "
                << response->DebugString() << "\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;
    using System;
    
    public class DetachSubscriptionSample
    {
        public void DetachSubscription(string projectId, string subscriptionId)
        {
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
    
            DetachSubscriptionRequest detachSubscriptionRequest = new DetachSubscriptionRequest
            {
                SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
            };
    
            publisher.DetachSubscription(detachSubscriptionRequest);
    
            Console.WriteLine($"Subscription {subscriptionId} is detached.");
        }
    }

    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 detachSubscription(w io.Writer, projectID, subName string) error {
    	// projectID is the project which contains the topic you manage.
    	// This might differ from the project which contains the subscription
    	// you wish to detach, which can exist in any GCP project.
    	// projectID := "my-project-id"
    	// subName := "projects/some-project/subscriptions/my-sub"
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	// Call DetachSubscription, which detaches a subscription from
    	// a topic. This can only be done if you have the
    	// `pubsub.topics.detachSubscription` role on the topic the
    	// subscription is attached to.
    	req := &pubsubpb.DetachSubscriptionRequest{
    		Subscription: subName,
    	}
    	_, err = client.TopicAdminClient.DetachSubscription(ctx, req)
    	if err != nil {
    		return fmt.Errorf("detach subscription failed: %w", err)
    	}
    
    	fmt.Fprintf(w, "Detached subscription %s", subName)
    	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.cloud.pubsub.v1.SubscriptionAdminClient;
    import com.google.cloud.pubsub.v1.TopicAdminClient;
    import com.google.pubsub.v1.DetachSubscriptionRequest;
    import com.google.pubsub.v1.Subscription;
    import com.google.pubsub.v1.SubscriptionName;
    import java.io.IOException;
    
    public class DetachSubscriptionExample {
      public static void main(String... args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        // Choose an existing subscription.
        String subscriptionId = "your-subscription-id";
    
        detachSubscriptionExample(projectId, subscriptionId);
      }
    
      public static void detachSubscriptionExample(String projectId, String subscriptionId)
          throws IOException {
        SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
    
        try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
          topicAdminClient.detachSubscription(
              DetachSubscriptionRequest.newBuilder()
                  .setSubscription(subscriptionName.toString())
                  .build());
        }
    
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
          Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
          if (subscription.getDetached()) {
            System.out.println("Subscription is detached.");
          } else {
            System.out.println("Subscription is NOT detached.");
          }
        }
      }
    }

    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 these variables before running the sample.
     */
    // const subscriptionNameOrId = 'YOUR_EXISTING_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 detachSubscription(subscriptionNameOrId) {
      // Gets the status of the existing subscription
      const sub = pubSubClient.subscription(subscriptionNameOrId);
      const [detached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`,
      );
    
      await pubSubClient.detachSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);
    
      const [updatedDetached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`,
      );
    }

    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 these variables before running the sample.
     */
    // const subscriptionNameOrId = 'YOUR_EXISTING_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 detachSubscription(subscriptionNameOrId: string) {
      // Gets the status of the existing subscription
      const sub = pubSubClient.subscription(subscriptionNameOrId);
      const [detached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`,
      );
    
      await pubSubClient.detachSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);
    
      const [updatedDetached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`,
      );
    }

    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;
    
    /**
     * Detach a Pub/Sub subscription from a topic.
     *
     * @param string $projectId  The Google project ID.
     * @param string $subscriptionName  The Pub/Sub subscription name.
     */
    function detach_subscription($projectId, $subscriptionName)
    {
        $pubsub = new PubSubClient([
            'projectId' => $projectId,
        ]);
        $subscription = $pubsub->subscription($subscriptionName);
        $subscription->detach();
    
        printf('Subscription detached: %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.api_core.exceptions import GoogleAPICallError, RetryError
    from google.cloud import pubsub_v1
    
    # TODO(developer): Choose an existing subscription.
    # project_id = "your-project-id"
    # subscription_id = "your-subscription-id"
    
    publisher_client = pubsub_v1.PublisherClient()
    subscriber_client = pubsub_v1.SubscriberClient()
    subscription_path = subscriber_client.subscription_path(project_id, subscription_id)
    
    try:
        publisher_client.detach_subscription(
            request={"subscription": subscription_path}
        )
    except (GoogleAPICallError, RetryError, ValueError, Exception) as err:
        print(err)
    
    subscription = subscriber_client.get_subscription(
        request={"subscription": subscription_path}
    )
    if subscription.detached:
        print(f"{subscription_path} is detached.")
    else:
        print(f"{subscription_path} is NOT detached.")

    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.

    # subscription_id = "your-subscription-id"
    
    pubsub = Google::Cloud::PubSub.new
    topic_admin = pubsub.topic_admin
    subscription_admin = pubsub.subscription_admin
    subscription_path = pubsub.subscription_path subscription_id
    
    topic_admin.detach_subscription subscription: subscription_path
    sleep 120
    subscription = subscription_admin.get_subscription \
      subscription: subscription_path
    
    if subscription.detached
      puts "Subscription is detached."
    else
      puts "Subscription is NOT detached."
    end

Layanan Pub/Sub mungkin memerlukan waktu beberapa menit untuk menyelesaikan pelepasan langganan dari topik.

Setelah layanan Pub/Sub melepaskan langganan dari topik, layanan Pub/Sub akan menghapus pesan apa pun yang dipertahankan untuk langganan. Anda tidak dapat mengambil pesan ini dari langganan atau melampirkan kembali langganan ke topik. Untuk mengosongkan kuota project, hapus langganan. Trusted Cloud

Jika langganan dan topik berada di Trusted Cloud project yang berbeda, layanan Pub/Sub akan menambahkan entri ke log audit kedua project tersebut.

Langkah berikutnya

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