Mengubah jenis langganan

Setelah membuat langganan, Anda dapat mengubah metode pengiriman menjadi push, pull, atau ekspor.

Sebelum memulai

Peran dan izin yang diperlukan

Untuk mendapatkan izin yang diperlukan untuk mengubah jenis langganan, minta administrator Anda 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 yang telah ditentukan ini berisi izin pubsub.subscriptions.update , yang diperlukan untuk mengubah jenis langganan.

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.

Mengubah jenis pengiriman langganan

Untuk mengubah jenis pengiriman langganan, lakukan langkah-langkah berikut.

Konsol

  1. Di Google Cloud konsol, buka halaman Subscriptions.

    Buka Langganan

  2. Klik nama langganan yang ingin Anda perbarui.

  3. Di halaman detail langganan, klik Edit.

  4. Untuk Delivery type, pilih jenis pengiriman baru.

  5. Isi properti untuk jenis langganan baru. Untuk mengetahui informasi selengkapnya, lihat topik berikut:

  6. Opsional. Perbarui properti langganan lainnya sesuai kebutuhan.

  7. Klik Update.

gcloud

Untuk mengubah jenis pengiriman, gunakan gcloud pubsub subscriptions update perintah. Hapus konfigurasi untuk jenis pengiriman saat ini dan tetapkan konfigurasi untuk jenis baru, sebagai berikut:

gcloud pubsub subscriptions update SUBSCRIPTION_ID \
  CLEAR_CONFIG_FLAG \
  NEW_CONFIG_FLAGS

Ganti kode berikut:

  • SUBSCRIPTION_ID: Nama langganan yang akan di update.

  • CLEAR_CONFIG_FLAG: Flag untuk menghapus konfigurasi yang ada untuk jenis pengiriman. Gunakan salah satu flag berikut, bergantung pada jenis pengiriman saat ini:

    • Langganan pull: --no-enable-exactly-once-delivery

    • Langganan push: --push-endpoint=""

    • Langganan BigQuery: --clear-bigquery-config

    • Langganan Cloud Storage: --clear-cloud-storage-config

  • NEW_CONFIG_FLAGS: Flag untuk mengonfigurasi jenis pengiriman baru. Untuk mengetahui informasi selengkapnya, lihat dokumentasi untuk gcloud pubsub subscriptions update perintah.

Contoh

Mengubah langganan BigQuery menjadi langganan pull:

gcloud pubsub subscriptions update SUBSCRIPTION_ID \
  --clear-bigquery-config

Mengubah langganan push menjadi langganan BigQuery:

gcloud pubsub subscriptions update SUBSCRIPTION_ID \
  --push-endpoint="" \
  --bigquery-table=BIGQUERY_TABLE

Memperbarui endpoint langganan push

Untuk memperbarui URL endpoint pada langganan push, lakukan langkah-langkah berikut.

Konsol

Untuk mengubah URL endpoint, lakukan langkah-langkah berikut.

  1. Di Google Cloud konsol, buka halaman Subscriptions.

    Buka Langganan

  2. Klik di samping langganan yang akan diupdate.
  3. Di Delivery type, pilih opsi pengiriman.
  4. Isi properti langganan lainnya sesuai kebutuhan.
  5. Klik Update.

gcloud

  1. Di Google Cloud konsol, aktifkan Cloud Shell.

    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 mengubah URL endpoint, jalankan perintah gcloud pubsub subscriptions modify-push-config

    gcloud pubsub subscriptions modify-push-config SUBSCRIPTION_ID \
      --push-endpoint=PUSH_ENDPOINT

    Jika langganan sudah menggunakan pengiriman pull, menetapkan endpoint push akan mengalihkan metode pengiriman ke pengiriman push.

    Anda dapat beralih dari pengiriman push ke pull dengan mengubah endpoint push menjadi string kosong.

REST

Untuk mengubah konfigurasi push langganan, gunakan projects.subscriptions.modifyPushConfig metode:

Permintaan:

Permintaan harus diautentikasi dengan token akses di the Authorization header. Untuk mendapatkan token akses untuk Kredensial Default Aplikasi saat ini: gcloud auth application-default print-access-token.

POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:modifyPushConfig
Authorization: Bearer ACCESS_TOKEN
  

Isi permintaan:

{
"pushConfig": {
  "pushEndpoint": "PUSH_ENDPOINT"
}
}

Dengan:

  • PROJECT_ID adalah project ID Anda.
  • SUBSCRIPTION_ID adalah ID langganan Anda.
  • PUSH_ENDPOINT adalah URL yang diubah yang ingin Anda terapkan sebagai endpoint push baru. Misalnya, https://myproject.appspot.com/myhandler.
  • 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 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,
       std::string const& endpoint) {
      google::pubsub::v1::ModifyPushConfigRequest request;
      request.set_subscription(
          pubsub::Subscription(project_id, subscription_id).FullName());
      request.mutable_push_config()->set_push_endpoint(endpoint);
      auto status = client.ModifyPushConfig(request);
      if (!status.ok()) throw std::runtime_error(status.message());
    
      std::cout << "The subscription push configuration was successfully"
                << " modified\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 UpdatePushConfigurationSample
    {
        public void UpdatePushConfiguration(string projectId, string subscriptionId, string pushEndpoint)
        {
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
    
            PushConfig pushConfig = new PushConfig { PushEndpoint = pushEndpoint };
    
            subscriber.ModifyPushConfig(subscriptionName, pushConfig);
        }
    }

    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"
    	"google.golang.org/protobuf/types/known/fieldmaskpb"
    )
    
    func updateEndpoint(w io.Writer, projectID, subscriptionName, endpoint string) error {
    	// projectID := "my-project-id"
    	// subscriptionName := "projects/my-project/subscriptions/my-sub"
    	// endpoint := "https://my-test-project.appspot.com/push"
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &pubsubpb.UpdateSubscriptionRequest{
    		Subscription: &pubsubpb.Subscription{
    			Name: subscriptionName,
    			PushConfig: &pubsubpb.PushConfig{
    				PushEndpoint: endpoint,
    			},
    		},
    		UpdateMask: &fieldmaskpb.FieldMask{
    			Paths: []string{"push_config"},
    		},
    	}
    	subConfig, err := client.SubscriptionAdminClient.UpdateSubscription(ctx, req)
    	if err != nil {
    		return fmt.Errorf("Update: %w", err)
    	}
    	fmt.Fprintf(w, "Updated subscription config: %v\n", subConfig)
    	return nil
    }
    

    Java

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Pub/Sub.

    
    import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
    import com.google.pubsub.v1.PushConfig;
    import com.google.pubsub.v1.Subscription;
    import com.google.pubsub.v1.SubscriptionName;
    import java.io.IOException;
    
    public class UpdatePushConfigurationExample {
      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";
        String pushEndpoint = "https://my-test-project.appspot.com/push";
    
        updatePushConfigurationExample(projectId, subscriptionId, pushEndpoint);
      }
    
      public static void updatePushConfigurationExample(
          String projectId, String subscriptionId, String pushEndpoint) throws IOException {
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
          SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
          PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).build();
          subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
          Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
          System.out.println(
              "Updated push endpoint to: " + subscription.getPushConfig().getPushEndpoint());
        }
      }
    }

    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 topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
    // 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 modifyPushConfig(topicNameOrId, subscriptionNameOrId) {
      const options = {
        // Set to an HTTPS endpoint of your choice. If necessary, register
        // (authorize) the domain on which the server is hosted.
        pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`,
      };
    
      await pubSubClient
        .topic(topicNameOrId)
        .subscription(subscriptionNameOrId)
        .modifyPushConfig(options);
      console.log(`Modified push config for subscription ${subscriptionNameOrId}.`);
    }

    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 topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
    // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';
    
    // Imports the Google Cloud client library
    import {PubSub, CreateSubscriptionOptions} from '@google-cloud/pubsub';
    
    // Creates a client; cache this for further use
    const pubSubClient = new PubSub();
    
    async function modifyPushConfig(
      topicNameOrId: string,
      subscriptionNameOrId: string,
    ) {
      const options: CreateSubscriptionOptions = {
        // Set to an HTTPS endpoint of your choice. If necessary, register
        // (authorize) the domain on which the server is hosted.
        pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`,
      };
    
      await pubSubClient
        .topic(topicNameOrId)
        .subscription(subscriptionNameOrId)
        .modifyPushConfig(options);
      console.log(`Modified push config for subscription ${subscriptionNameOrId}.`);
    }

    Python

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Pub/Sub.

    from google.cloud import pubsub_v1
    
    # TODO(developer)
    # project_id = "your-project-id"
    # topic_id = "your-topic-id"
    # subscription_id = "your-subscription-id"
    # endpoint = "https://my-test-project.appspot.com/push"
    
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path(project_id, subscription_id)
    
    push_config = pubsub_v1.types.PushConfig(push_endpoint=endpoint)
    
    subscription = pubsub_v1.types.Subscription(
        name=subscription_path, topic=topic_id, push_config=push_config
    )
    
    update_mask = {"paths": {"push_config"}}
    
    # Wrap the subscriber in a 'with' block to automatically call close() to
    # close the underlying gRPC channel when done.
    with subscriber:
        result = subscriber.update_subscription(
            request={"subscription": subscription, "update_mask": update_mask}
        )
    
    print(f"Subscription updated: {subscription_path}")
    print(f"New endpoint for subscription is: {result.push_config}.")

    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"
    # new_endpoint      = "Endpoint where your app receives messages""
    
    pubsub = Google::Cloud::PubSub.new
    subscription_admin = pubsub.subscription_admin
    
    subscription = subscription_admin.get_subscription \
      subscription: pubsub.subscription_path(subscription_id)
    subscription.push_config = Google::Cloud::PubSub::V1::PushConfig.new \
      push_endpoint: new_endpoint
    
    subscription_admin.update_subscription subscription: subscription,
                                           update_mask: {
                                             paths: ["push_config"]
                                           }
    
    puts "Push endpoint updated."

    Langkah berikutnya