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

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

準備

必要なロールと権限

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

この事前定義ロールには、サブスクリプション タイプの変更と管理に必要な権限が含まれています。必要な権限を正確に確認するには、[必要な権限] セクションを開いてください。

必要な権限

サブスクリプション タイプを変更して管理するには、次の権限が必要です。

  • サブスクリプションから pull する: pubsub.subscriptions.consume
  • サブスクリプションを作成する: pubsub.subscriptions.create
  • サブスクリプションを削除する: pubsub.subscriptions.delete
  • サブスクリプションを取得する: pubsub.subscriptions.get
  • サブスクリプションを一覧表示する: pubsub.subscriptions.list
  • サブスクリプションを更新する: pubsub.subscriptions.update
  • サブスクリプションをトピックに接続する: pubsub.topics.attachSubscription
  • サブスクリプションの IAM ポリシーを取得する: pubsub.subscriptions.getIamPolicy
  • サブスクリプションの IAM ポリシーを構成する: pubsub.subscriptions.setIamPolicy

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

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

配信方法を変更する

異なるサブスクリプション タイプ間で切り替えることができます。

Console

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

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

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

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

gcloud

  1. Google Cloud コンソールで、「Cloud Shell をアクティブにする」をクリックします。

    Cloud Shell をアクティブにする

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

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

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

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

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

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++

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

    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#

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

    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

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

    Pub/Sub に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/pubsub"
    )
    
    func updateEndpoint(w io.Writer, projectID, subID string, endpoint string) error {
    	// projectID := "my-project-id"
    	// subID := "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()
    
    	subConfig, err := client.Subscription(subID).Update(ctx, pubsub.SubscriptionConfigToUpdate{
    		PushConfig: &pubsub.PushConfig{Endpoint: endpoint},
    	})
    	if err != nil {
    		return fmt.Errorf("Update: %w", err)
    	}
    	fmt.Fprintf(w, "Updated subscription config: %v\n", subConfig)
    	return nil
    }
    

    Java

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

    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

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

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

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

    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

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

    Pub/Sub に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    # subscription_id   = "your-subscription-id"
    # new_endpoint      = "Endpoint where your app receives messages""
    
    pubsub = Google::Cloud::Pubsub.new
    
    subscription          = pubsub.subscription subscription_id
    subscription.endpoint = new_endpoint
    
    puts "Push endpoint updated."

    次のステップ

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