サブスクリプション タイプの変更

サブスクリプションを作成したら、配信方法を push、pull、エクスポートに変更できます。

準備

必要なロールと権限

サブスクリプション タイプの変更に必要な権限を取得するには、サブスクリプションに対する Pub/Sub 編集者 roles/pubsub.editor)の IAM ロールを付与するように管理者に依頼してください。ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

この事前定義ロールには、サブスクリプション タイプの変更に必要な pubsub.subscriptions.update 権限が含まれています。

カスタムロールや他の事前定義ロールを使用して、この権限を取得することもできます。

アクセス制御は、プロジェクト レベルと個々のリソースレベルで構成できます。あるプロジェクトにサブスクリプションを作成し、別のプロジェクトにあるトピックにアタッチできます。プロジェクトごとに必要な権限があることを確認します。

サブスクリプションの配信タイプを変更する

サブスクリプションの配信タイプを変更する手順は次のとおりです。

コンソール

  1. コンソールで [**サブスクリプション**] ページに移動します。 Google Cloud

    [サブスクリプション] に移動

  2. 更新するサブスクリプションの名前をクリックします。

  3. サブスクリプションの詳細ページで [編集] をクリックします。

  4. [**配信タイプ**] で、新しい配信タイプを選択します。

  5. 新しいサブスクリプション タイプのプロパティを入力します。詳細については次のトピックをご覧ください。

  6. 省略可。必要に応じて、他のサブスクリプション プロパティを更新します。

  7. [更新] をクリックします。

gcloud

配信タイプを変更するには、 gcloud pubsub subscriptions update コマンドを使用します。現在の配信タイプの構成をクリアし、次のように新しいタイプの構成を設定します。

gcloud pubsub subscriptions update SUBSCRIPTION_ID \
  CLEAR_CONFIG_FLAG \
  NEW_CONFIG_FLAGS

次のように置き換えます。

  • SUBSCRIPTION_ID: 更新するサブスクリプションの名前。

  • CLEAR_CONFIG_FLAG: 配信タイプの既存の 構成をクリアするフラグ。現在の配信タイプに応じて、次のいずれかのフラグを使用します。

    • pull サブスクリプション: --no-enable-exactly-once-delivery

    • push サブスクリプション: --push-endpoint=""

    • BigQuery サブスクリプション: --clear-bigquery-config

    • Cloud Storage サブスクリプション: --clear-cloud-storage-config

  • NEW_CONFIG_FLAGS: 新しい 配信タイプを構成するフラグ。詳細については、 gcloud pubsub subscriptions update コマンドのドキュメントをご覧ください。

BigQuery サブスクリプションを pull サブスクリプションに変更する:

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

push サブスクリプションを BigQuery サブスクリプションに変更する:

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

push サブスクリプションのエンドポイントを更新する

push サブスクリプションのエンドポイント URLを更新する手順は次のとおりです。

コンソール

エンドポイント URL を変更する手順は次のとおりです。

  1. コンソールで [**サブスクリプション**] ページに移動します。 Google Cloud

    [サブスクリプション] に移動

  2. 更新するサブスクリプションの横の をクリックします。
  3. In the [**配信タイプ**] で、配信オプションを選択します。
  4. 必要に応じて、他のサブスクリプション プロパティを入力します。
  5. [更新] をクリックします。

gcloud

  1. コンソールで Cloud Shell をアクティブにします。 Google Cloud

    Cloud Shell をアクティブにする

    コンソールの下部にある Google Cloud Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です 。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています 。セッションが初期化されるまで数秒かかることがあります。

  2. エンドポイント URL を変更するには、gcloud pubsub subscriptions modify-push-config コマンドを実行します。

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

    サブスクリプションで pull 配信がすでに使用されている場合、push エンドポイントを設定すると 配信方法が push 配信に切り替わります。

    push エンドポイントを 空の文字列に変更すると、push 配信から pull 配信に切り替えることができます。

REST

サブスクリプションの push 構成を変更するには、 projects.subscriptions.modifyPushConfig メソッドを使用します。

リクエスト:

リクエストは、 Authorization ヘッダー内のアクセス トークンにより認証を受ける必要があります。現在の アプリケーションのデフォルト認証情報のアクセス トークンを取得する場合は、gcloud auth application-default print-access-tokenを使用します。

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

リクエスト本文:

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

ここで

  • PROJECT_ID はプロジェクト ID です。
  • SUBSCRIPTION_ID はサブスクリプション ID です。
  • PUSH_ENDPOINT は、新しい push エンドポイントとしての適用先にする、変更済みの URL です。例: https://myproject.appspot.com/myhandler
  • レスポンス:

    リクエストが成功した場合のレスポンスは空の JSON オブジェクトです。

    C++

    このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C++ の設定手順を実施してください。詳細については、Pub/Sub C++ API リファレンス ドキュメントをご覧ください。

    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#

    このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、Pub/Sub C# API リファレンス ドキュメントをご覧ください。

    
    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

    次のサンプルでは、Go Pub/Sub クライアント ライブラリのメジャー バージョン(v2)を使用します。v1 ライブラリをまだ使用している場合は、 v2 への移行ガイドをご覧ください。 v1 コードサンプルのリストについては、 非推奨のコードサンプルをご覧ください。

    このサンプルを試す前に、 クイックスタート: クライアント ライブラリの使用の Go の設定手順を実施してください。 詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

    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

    このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。

    
    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

    このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API リファレンス ドキュメントをご覧ください。

    /**
     * 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

    このサンプルを試す前に、 クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。 詳細については、Pub/Sub Node.js API リファレンス ドキュメントをご覧ください。

    /**
     * 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

    このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Python の設定手順を実施してください。詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

    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

    次のサンプルでは、Ruby Pub/Sub クライアント ライブラリ v3 を使用します。v2 ライブラリをまだ使用している場合は、 v3 への移行ガイドをご覧ください。 Ruby v2 コードサンプルのリストについては、 非推奨のコードサンプルをご覧ください。

    このサンプルを試す前に、 クイックスタート: クライアント ライブラリの使用の Ruby の設定手順を実施してください。 詳細については、Pub/Sub Ruby API リファレンス ドキュメントをご覧ください。

    # 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."

    次のステップ

    • gcloud コマンドを使用して、サブスクリプションを作成または変更する。
    • REST API を使用してサブスクリプションを作成または変更する。