イベント ドリブン関数を作成する
Cloud Run functions では、クラウド環境で発生したイベントに応じて関数を自動的に呼び出す場合に、イベント ドリブン関数を使用します。
CloudEvent 関数
CloudEvent 関数を使用して関数を呼び出します。
CloudEvent 関数は、イベントデータを一般的な方法で記述するための業界標準である CloudEvents をベースにしています。CloudEvents 仕様の詳細については、CloudEvents GitHub リポジトリをご覧ください。CloudEvents プロジェクトには、コード内の CloudEvents オブジェクトを操作するための一連の CloudEvents SDK も用意されています。
以下に、各ランタイムの基本的な CloudEvent 関数のソースファイルを示します。ソースコードの場所については、ソース ディレクトリ構造をご覧ください。
const functions = require('@google-cloud/functions-framework');
// Register a CloudEvent function with the Functions Framework
functions.cloudEvent('myCloudEventFunction', cloudEvent => {
// Your code here
// Access the CloudEvent data payload via cloudEvent.data
});
Node.js では、CloudEvent ハンドラ関数を Functions Framework for Node.js で登録します。ハンドラ関数は、CloudEvent
オブジェクトを引数として受け入れる必要があります。
関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは myCloudEventFunction
です。
import functions_framework
# Register a CloudEvent function with the Functions Framework
@functions_framework.cloud_event
def my_cloudevent_function(cloud_event):
# Your code here
# Access the CloudEvent data payload via cloud_event.data
Python では、CloudEvent ハンドラ関数を Functions Framework for Python に登録します。ハンドラ関数は、CloudEvent
オブジェクトを引数として受け入れる必要があります。
関数のエントリ ポイントは、Functions Framework に登録されたハンドラ関数の名前です。この例では、エントリ ポイントは my_cloudevent_function
です。
package mycloudeventfunction
import (
"context"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
"github.com/cloudevents/sdk-go/v2/event"
)
func init() {
// Register a CloudEvent function with the Functions Framework
functions.CloudEvent("MyCloudEventFunction", myCloudEventFunction)
}
// Function myCloudEventFunction accepts and handles a CloudEvent object
func myCloudEventFunction(ctx context.Context, e event.Event) error {
// Your code here
// Access the CloudEvent data payload via e.Data() or e.DataAs(...)
// Returning an error causes its message to be logged.
// Example:
err := myInternalFunction() // may return an error
if err != nil {
// Append error message to log
return err
}
// Return nil if no error occurred
return nil
}
Go では、CloudEvent ハンドラ関数を Functions Framework for Go に登録します。ハンドラ関数は、CloudEvents event.Event
オブジェクトを引数として受け入れる必要があります。
関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは MyCloudEventFunction
です。
package mycloudeventfunction;
import com.google.cloud.functions.CloudEventsFunction;
import io.cloudevents.CloudEvent;
// Define a class that implements the CloudEventsFunction interface
public class MyCloudEventFunction implements CloudEventsFunction {
// Implement the accept() method to handle CloudEvents
@Override
public void accept(CloudEvent event) {
// Your code here
// Access the CloudEvent data payload via event.getData()
// To get the data payload as a JSON string, use:
// new String(event.getData().toBytes())
}
}
Java では、Functions Framework Java API を使用して、CloudEventsFunction
インターフェースを持つ CloudEvent ハンドラクラスを実装します。accept()
メソッドは、CloudEvent
オブジェクトを引数として受け取り、イベントに対する処理を行う必要があります。
関数のエントリ ポイントは、パッケージ名を含む CloudEvent ハンドラクラスの完全修飾名です。この例では、エントリ ポイントは mycloudeventfunction.MyCloudEventFunction
です。
using CloudNative.CloudEvents; using Google.Cloud.Functions.Framework; using System.Threading; using System.Threading.Tasks; namespace MyProject { // Define a class that implements the ICloudEventFunction<T> interface public class MyCloudEventFunction : ICloudEventFunction<CloudEventDataType > { // Implement the HandleAsync() method to handle CloudEvents public Task HandleAsync(CloudEvent cloudEvent,CloudEventDataType data, CancellationToken cancellationToken) { // Your code here // The data argument represents the CloudEvent data payload // Signal function completion return Task.CompletedTask; } } }
.NET ランタイムでは、Functions Framework for .NET を使用して、ICloudEventFunction<T>
インターフェースを持つ CloudEvent ハンドラクラスを実装します。HandleAsync()
メソッドは、引数として CloudEvent
オブジェクトとそれに関連する CloudEvent データ ペイロードを受け取ります。
CloudEvent データ ペイロード引数の型(上記の例では CloudEventDataType
)は、関数が処理するイベントのタイプに対応している必要があります。Google CloudEvents .NET ライブラリには、Google でサポートされているさまざまなイベントのデータ型が用意されています。
関数のエントリ ポイントは、CloudEvent ハンドラクラスの完全修飾名(名前空間を含む)です。この例では、エントリ ポイントは MyProject.MyCloudEventFunction
です。
require "functions_framework"
# Register a CloudEvent function with the Functions Framework
FunctionsFramework.cloud_event "my_cloudevent_function" do |cloud_event|
# Your code here
# Access the CloudEvent data payload via cloud_event.data
end
Ruby では、CloudEvent ハンドラ関数を Functions Framework for Ruby に登録します。ハンドラ関数は、CloudEvents Event
オブジェクトを引数として受け入れる必要があります。
関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは my_cloudevent_function
です。
<?php
use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;
// Register a CloudEvent function with the Functions Framework
FunctionsFramework::cloudEvent('myCloudEventFunction', 'myCloudEventHandler');
// Define your CloudEvent handler
function myCloudEventHandler(CloudEventInterface $event): void
{
// Your code here
// Access the CloudEvent data payload via $event->getData()
}
PHP では、CloudEvent ハンドラ関数を Functions Framework for PHP に登録します。ハンドラ関数は、CloudEventInterface
インターフェースに適合する引数を受け入れる必要があります。
関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは myCloudEventFunction
です。
CloudEvent 関数の場合、イベントデータは CloudEvents 形式で関数に渡されます。CloudEvent データ ペイロードは、関数をトリガーするイベントタイプに対応します。サポートされているトリガー、イベントタイプ、関連するイベントデータの形式については、Cloud Run 関数のトリガーをご覧ください。
Google イベント リポジトリには、Google が発行する CloudEvents を使用するためのリソースが含まれています。
関数の終了
関数から制御が戻ると、Cloud Run functions はイベント ドリブン関数の実行が終了したと判断します。関数によってバックグラウンド タスク(スレッド、Future、JavaScript Promise
オブジェクト、コールバック、システム プロセスなど)が作成される場合は、関数から制御が戻る前に、これらのタスクを終了します。あるいは、他の方法で問題を解決する必要があります。関数が返される前に終了しなかったタスクは完了しません。未定義の動作が行われる可能性があります。
自動再試行
失敗した呼び出しを自動的に再試行するように、イベント ドリブン関数を構成できます。詳細については、イベント ドリブン関数の再試行をご覧ください。
次のステップ
- Cloud Run 関数のトリガーについて学習する。
- Cloud Run 関数のデプロイ方法を学習する。
- チュートリアルで、イベント ドリブン関数の例など、Cloud Run functions のさまざまなユースケースの例について確認する。