pull サブスクリプションを作成する

このドキュメントでは、pull サブスクリプションを作成する方法について説明します。pull サブスクリプションを作成するには、 Google Cloud コンソール、Google Cloud CLI、クライアント ライブラリ、または Pub/Sub API を使用します。

始める前に

必要なロールと権限

サブスクリプションを作成するには、プロジェクト レベルでアクセス制御を構成する必要があります。このセクションで後述するように、サブスクリプションとトピックが異なるプロジェクトにある場合は、リソースレベルの権限も必要です。

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

この事前定義ロールには、pull サブスクリプションの作成に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

pull サブスクリプションを作成するには、次の権限が必要です。

  • サブスクリプションから 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

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

別のプロジェクトのトピックに関連付けられているプロジェクトで pull サブスクリプションを作成する必要がある場合は、トピック管理者にトピックに対する Pub/Sub 編集者の (roles/pubsub.editor) IAM ロールも付与するよう依頼してください。

pull サブスクリプション プロパティ

pull サブスクリプションを構成するときに、次のプロパティを指定できます。

共通の特徴

すべてのサブスクリプションで設定できる共通のサブスクリプション プロパティについて学習します。

1 回限りの配信

1 回限りの配信。設定すると、Pub/Sub によって 1 回限りの配信の保証が履行されます。指定しない場合、サブスクリプションでメッセージごとに少なくとも 1 回の配信がサポートされます。

pull サブスクリプションを作成する

次のサンプルは、指定されたデフォルト設定を使用して、pull 配信でサブスクリプションを作成する方法を示しています。

Console

pull サブスクリプションの作成は、次の手順で行います。

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

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

  2. [サブスクリプションを作成] をクリックします。
  3. [サブスクリプション ID] フィールドに名前を入力します。

    サブスクリプションの指定方法については、トピックまたはサブスクリプションの指定方法のガイドラインをご覧ください。

  4. プルダウン メニューからトピックを選択するか、作成します。サブスクリプションがトピックからメッセージを受信します。
  5. [配信タイプ] を Pull として保持します。
  6. 他のすべてのデフォルト値は保持されます。
  7. [作成] をクリックします。

[トピック] セクションからサブスクリプションを作成することもできます。このショートカットは、トピックとサブスクリプションの関連付けに使用できます。

  1. Google Cloud コンソールで、[トピック] ページに移動します。

    [トピック] に移動

  2. サブスクリプションを作成するトピックの横の をクリックします。
  3. コンテキスト メニューから [サブスクリプションを作成] を選択します。
  4. [サブスクリプション ID] を入力します。

    サブスクリプションの指定方法については、トピックまたはサブスクリプションの指定方法のガイドラインをご覧ください。

  5. [配信タイプ] を Pull として保持します。
  6. 他のすべてのデフォルト値は保持されます。
  7. [作成] をクリックします。

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google 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. pull サブスクリプションを作成するには、 gcloud pubsub subscriptions create コマンドを実行します。
    gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic=TOPIC_ID

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

    • SUBSCRIPTION_ID: 新しい pull サブスクリプションの名前または ID。
    • TOPIC_ID: トピックの名前または ID。
  3. REST

    pull サブスクリプションを作成するには、 projects.subscriptions.create メソッドを使用します。

    リクエスト:

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

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

    リクエスト本文:

    { "topic": "projects/PROJECT_ID/topics/TOPIC_ID" }

    ここで

    • PROJECT_ID はプロジェクト ID です。
    • SUBSCRIPTION_ID はサブスクリプション ID です。
    • TOPIC_ID はトピック ID です。

    レスポンス:

    { "name": "projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID", "topic": "projects/PROJECT_ID/topics/TOPIC_ID", "pushConfig": {}, "ackDeadlineSeconds": 10, "messageRetentionDuration": "604800s", "expirationPolicy": { "ttl": "2678400s" } }

    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& topic_id,    std::string const& subscription_id) {   google::pubsub::v1::Subscription request;   request.set_name(       pubsub::Subscription(project_id, subscription_id).FullName());   request.set_topic(pubsub::Topic(project_id, topic_id).FullName());   auto sub = client.CreateSubscription(request);   if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {     std::cout << "The subscription already exists\n";     return;   }   if (!sub) throw std::move(sub).status();    std::cout << "The subscription was successfully created: "             << sub->DebugString() << "\n"; }

    C#

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

     using Google.Cloud.PubSub.V1; using Grpc.Core;  public class CreateSubscriptionSample {     public Subscription CreateSubscription(string projectId, string topicId, string subscriptionId)     {         SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();         TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);          SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);         Subscription subscription = null;          try         {             subscription = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);         }         catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)         {             // Already exists.  That's fine.         }         return subscription;     } }

    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" )  func create(w io.Writer, projectID, topic, subscription string) error { 	// projectID := "my-project-id" 	// topic := "projects/my-project-id/topics/my-topic" 	// subscription := "projects/my-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()  	sub, err := client.SubscriptionAdminClient.CreateSubscription(ctx, &pubsubpb.Subscription{ 		Name:  subscription, 		Topic: topic, 	}) 	if err != nil { 		return fmt.Errorf("CreateSubscription: %w", err) 	} 	fmt.Fprintf(w, "Created subscription: %v\n", sub) 	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 com.google.pubsub.v1.TopicName; import java.io.IOException;  public class CreatePullSubscriptionExample {   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 topicId = "your-topic-id";      createPullSubscriptionExample(projectId, subscriptionId, topicId);   }    public static void createPullSubscriptionExample(       String projectId, String subscriptionId, String topicId) throws IOException {     try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {       TopicName topicName = TopicName.of(projectId, topicId);       SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);       // Create a pull subscription with default acknowledgement deadline of 10 seconds.       // Messages not successfully acknowledged within 10 seconds will get resent by the server.       Subscription subscription =           subscriptionAdminClient.createSubscription(               subscriptionName, topicName, PushConfig.getDefaultInstance(), 10);       System.out.println("Created pull subscription: " + subscription.getName());     }   } }

    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 createSubscription(topicNameOrId, subscriptionNameOrId) {   // Creates a new subscription   await pubSubClient     .topic(topicNameOrId)     .createSubscription(subscriptionNameOrId);   console.log(`Subscription ${subscriptionNameOrId} created.`); }

    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} from '@google-cloud/pubsub';  // Creates a client; cache this for further use const pubSubClient = new PubSub();  async function createSubscription(   topicNameOrId: string,   subscriptionNameOrId: string, ) {   // Creates a new subscription   await pubSubClient     .topic(topicNameOrId)     .createSubscription(subscriptionNameOrId);   console.log(`Subscription ${subscriptionNameOrId} created.`); }

    PHP

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

    use Google\Cloud\PubSub\PubSubClient;  /**  * Creates a Pub/Sub subscription.  *  * @param string $projectId  The Google project ID.  * @param string $topicName  The Pub/Sub topic name.  * @param string $subscriptionName  The Pub/Sub subscription name.  */ function create_subscription($projectId, $topicName, $subscriptionName) {     $pubsub = new PubSubClient([         'projectId' => $projectId,     ]);     $topic = $pubsub->topic($topicName);     $subscription = $topic->subscription($subscriptionName);     $subscription->create();      printf('Subscription created: %s' . PHP_EOL, $subscription->name()); }

    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"  publisher = pubsub_v1.PublisherClient() subscriber = pubsub_v1.SubscriberClient() topic_path = publisher.topic_path(project_id, topic_id) 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:     subscription = subscriber.create_subscription(         request={"name": subscription_path, "topic": topic_path}     )  print(f"Subscription created: {subscription}")

    Ruby

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

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

    # topic_id        = "your-topic-id" # subscription_id = "your-subscription-id"  pubsub = Google::Cloud::PubSub.new subscription_admin = pubsub.subscription_admin  subscription = subscription_admin.create_subscription \   name: pubsub.subscription_path(subscription_id),   topic: pubsub.topic_path(topic_id)  puts "Pull subscription #{subscription_id} created."

pull サブスクリプションのモニタリング

Cloud Monitoring には、サブスクリプションをモニタリングするための指標が多数用意されています。

Pub/Sub に関連する使用可能なすべての指標のリストとその説明については、Pub/Sub のモニタリング ドキュメントをご覧ください。

Pub/Sub 内からサブスクリプションをモニタリングすることもできます。

次のステップ