Cloud Pub/Sub のチュートリアル(第 1 世代)


このシンプルなチュートリアルでは、Pub/Sub トリガーを使用して Cloud Run functions イベント ドリブン関数を作成、デプロイ、トリガーする方法について説明します。

Pub/Sub を初めて使用する場合、詳細については Pub/Sub のドキュメント、特にトピックとサブスクリプションの管理をご覧ください。Cloud Run functions での Pub/Sub トピックとサブスクリプションの使用に関する概要については、Pub/Sub トリガーをご覧ください。

Pub/Sub 自体を使用したコードサンプルについては、サンプル ブラウザをご覧ください。

目標

費用

このドキュメントでは、課金対象である次の Google Cloudコンポーネントを使用します。

  • Cloud Run functions
  • Pub/Sub

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。

新規の Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

始める前に

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  7. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  13. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  14. gcloud CLI がすでにインストールされている場合は、次のコマンドを実行して更新します。

    gcloud components update
  15. 開発環境を準備します。
  16. アプリケーションの準備

    1. ローカルマシンにサンプルアプリのリポジトリのクローンを作成します。

      Node.js

      git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

      Python

      git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

      Go

      git clone https://github.com/GoogleCloudPlatform/golang-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

      Java

      git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

      または、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

      Ruby

      git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    2. Pub/Sub にアクセスするための Cloud Run functions サンプルコードがあるディレクトリに移動します。

      Node.js

      cd nodejs-docs-samples/functions/helloworld/

      Python

      cd python-docs-samples/functions/helloworld/

      Go

      cd golang-samples/functions/helloworld/

      Java

      cd java-docs-samples/functions/helloworld/hello-pubsub/

      Ruby

      cd ruby-docs-samples/functions/helloworld/pubsub/

    3. サンプルコードを見てみましょう。

      Node.js

      /**
       * Background Cloud Function to be triggered by Pub/Sub.
       * This function is exported by index.js, and executed when
       * the trigger topic receives a message.
       *
       * @param {object} message The Pub/Sub message.
       * @param {object} context The event metadata.
       */
      exports.helloPubSub = (message, context) => {
        const name = message.data
          ? Buffer.from(message.data, 'base64').toString()
          : 'World';
      
        console.log(`Hello, ${name}!`);
      };

      Python

      def hello_pubsub(event, context):
          """Background Cloud Function to be triggered by Pub/Sub.
          Args:
               event (dict):  The dictionary with data specific to this type of
                              event. The `@type` field maps to
                               `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                              The `data` field maps to the PubsubMessage data
                              in a base64-encoded string. The `attributes` field maps
                              to the PubsubMessage attributes if any is present.
               context (google.cloud.functions.Context): Metadata of triggering event
                              including `event_id` which maps to the PubsubMessage
                              messageId, `timestamp` which maps to the PubsubMessage
                              publishTime, `event_type` which maps to
                              `google.pubsub.topic.publish`, and `resource` which is
                              a dictionary that describes the service API endpoint
                              pubsub.googleapis.com, the triggering topic's name, and
                              the triggering event type
                              `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
          Returns:
              None. The output is written to Cloud Logging.
          """
          import base64
      
          print(
              """This Function was triggered by messageId {} published at {} to {}
          """.format(
                  context.event_id, context.timestamp, context.resource["name"]
              )
          )
      
          if "data" in event:
              name = base64.b64decode(event["data"]).decode("utf-8")
          else:
              name = "World"
          print(f"Hello {name}!")
      
      

      Go

      
      // Package helloworld provides a set of Cloud Functions samples.
      package helloworld
      
      import (
      	"context"
      	"log"
      )
      
      // PubSubMessage is the payload of a Pub/Sub event.
      // See the documentation for more details:
      // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
      type PubSubMessage struct {
      	Data []byte `json:"data"`
      }
      
      // HelloPubSub consumes a Pub/Sub message.
      func HelloPubSub(ctx context.Context, m PubSubMessage) error {
      	name := string(m.Data) // Automatically decoded from base64.
      	if name == "" {
      		name = "World"
      	}
      	log.Printf("Hello, %s!", name)
      	return nil
      }
      

      Java

      
      import com.google.cloud.functions.BackgroundFunction;
      import com.google.cloud.functions.Context;
      import functions.eventpojos.PubsubMessage;
      import java.nio.charset.StandardCharsets;
      import java.util.Base64;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      
      public class HelloPubSub implements BackgroundFunction<PubsubMessage> {
        private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());
      
        @Override
        public void accept(PubsubMessage message, Context context) {
          String name = "world";
          if (message != null && message.getData() != null) {
            name = new String(
                Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
                StandardCharsets.UTF_8);
          }
          logger.info(String.format("Hello %s!", name));
          return;
        }
      }

      Ruby

      require "functions_framework"
      require "base64"
      
      FunctionsFramework.cloud_event "hello_pubsub" do |event|
        # The event parameter is a CloudEvents::Event::V1 object.
        # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
        name = Base64.decode64 event.data["message"]["data"] rescue "World"
      
        # A cloud_event function does not return a response, but you can log messages
        # or cause side effects such as sending additional events.
        logger.info "Hello, #{name}!"
      end

    関数のデプロイ

    Pub/Sub トリガーを使用して関数をデプロイするには、サンプルコード(Java の場合は pom.xml ファイル)を含むディレクトリで次のコマンドを実行します。

    Node.js

    gcloud functions deploy helloPubSub \
    --runtime nodejs20 \
    --trigger-topic YOUR_TOPIC_NAME

    サポートされている Node.js バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Python

    gcloud functions deploy hello_pubsub \
    --runtime python312 \
    --trigger-topic YOUR_TOPIC_NAME

    サポートされている Python バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Go

    gcloud functions deploy HelloPubSub \
    --runtime go121 \
    --trigger-topic YOUR_TOPIC_NAME

    サポートされている Go バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Java

    gcloud functions deploy java-pubsub-function \
    --entry-point functions.HelloPubSub \
    --runtime java17 \
    --memory 512MB \
    --trigger-topic YOUR_TOPIC_NAME

    サポートされている Java バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Ruby

    gcloud functions deploy hello_pubsub --runtime ruby33 \
    -
    -trigger-topic YOUR_TOPIC_NAME

    サポートされている Ruby バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    ここで、YOUR_TOPIC_NAME は関数の登録先となる Pub/Sub トピックの名前です。

    YOUR_TOPIC_NAME がまだ存在しない場合、このコマンドにより作成されます。Google Cloud コンソールまたは次の gcloud コマンドを使用して、deploy コマンドを実行する前にトピックを作成することもできます。

    gcloud pubsub topics create YOUR_TOPIC_NAME

    関数のトリガー

    1. メッセージを Pub/Sub トピックに公開します。この例では、メッセージは関数が挨拶に含める名前です。

      gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

      YOUR_TOPIC_NAME を Pub/Sub トピックの名前に置き換え、YOUR_NAME を任意の文字列に置き換えます。

    2. 実行した内容が完了していることをログで確認します。

      gcloud functions logs read --limit 50

    関数内からメッセージを Pub/Sub トピックに公開することもできます。

    クリーンアップ

    このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。

    プロジェクトの削除

    課金されないようにする最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。

    プロジェクトを削除するには:

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    関数の削除

    Cloud Run functions を削除しても、Cloud Storage に保存されたリソースは削除されません。

    このチュートリアルで作成した関数を削除するには、次のコマンドを実行します。

    Node.js

    gcloud functions delete helloPubSub 

    Python

    gcloud functions delete hello_pubsub 

    Go

    gcloud functions delete HelloPubSub 

    Java

    gcloud functions delete java-pubsub-function 

    Ruby

    gcloud functions delete hello_pubsub 

    Cloud Run functions の関数は Google Cloud コンソールで削除することもできます。