編寫事件導向的 Cloud Run 函式

在 Cloud Run 函式中,如果您希望函式能直接觸發,以回應Google Cloud 專案中的事件 (例如 Pub/Sub 主題上的訊息或 Cloud Storage 值區中的變更),請撰寫事件驅動函式。

實作事件導向的處理常式函式

事件導向函式以 CloudEvents 為基礎,這是一種業界標準規格,可用於以常見方式描述事件資料。如要進一步瞭解 CloudEvents 規格,請前往 CloudEvents GitHub 存放區。CloudEvents 專案也提供一組 CloudEvents SDK,協助您在程式碼中使用 CloudEvents 物件。

以下範例顯示每個執行階段的事件驅動函式來源檔案。如要瞭解原始碼的位置,請參閱「來源目錄結構」。

Node.js

ES 模組

  import { cloudEvent } from "@google-cloud/functions-framework";   cloudEvent('myCloudEventFunction', cloudEvent => {     // Your code here     // Access the CloudEvent data payload using cloudEvent.data   }); 

package.json 檔案中新增下列依附元件,包括 "type": "module"

  {     "dependencies": {       "@google-cloud/functions-framework": "^3.0.0"     },     "type": "module"   } 

CommonJS 模組

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 using cloudEvent.data }); 

package.json 檔案中新增下列依附元件:

  {     "dependencies": {       "@google-cloud/functions-framework": "^3.0.0"     }   } 

在 Node.js 中,您可以使用 Node.js 專用的 Functions Framework 註冊 CloudEvent 處理常式函式。處理常式函式必須接受 CloudEvent 物件做為引數。

函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 myCloudEventFunction

Python

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 中,您可以使用 Python 版 Functions Framework 註冊 CloudEvent 處理常式函式。處理常式函式必須接受 CloudEvent 物件做為引數。

函式進入點是指向 Functions Framework 註冊的處理常式函式名稱。在這個範例中,進入點為 my_cloudevent_function

Go

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 using 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 中,您可以使用 Go 專用 Functions Framework 註冊 CloudEvent 處理常式函式。處理常式函式必須接受 CloudEvents event.Event 物件做為引數。

函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 MyCloudEventFunction

Java

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

.NET

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 執行階段中,您可以使用 .NET 專用函式架構,透過 ICloudEventFunction<T> 介面實作 CloudEvent 處理常式類別。HandleAsync() 方法會接受 CloudEvent 物件和相關聯的 CloudEvent 資料酬載做為引數。

CloudEvent 資料酬載引數的類型 (在範例程式碼中顯示為 CloudEventDataType) 必須對應至函式處理的事件類型。Google CloudEvents .NET 程式庫提供 Google 支援的各種事件資料類型。

函式進入點是 CloudEvent 處理常式類別的完整名稱,包括命名空間。在這個範例中,進入點為 MyProject.MyCloudEventFunction

Ruby

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 中,您可以使用 Ruby 版 Functions Framework 註冊 CloudEvent 處理常式函式。處理常式函式必須接受 CloudEvents Event 物件做為引數。

函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 my_cloudevent_function

PHP

<?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 using $event->getData() } 

在 PHP 中,您可以使用 PHP 版 Functions Framework 註冊 CloudEvent 處理常式函式。處理常式函式必須接受符合 CloudEventInterface 介面的引數。

函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 myCloudEventFunction

對於事件驅動函式,事件資料會以 CloudEvents 格式傳遞至函式,其中 CloudEvent 資料酬載會對應至觸發函式的事件類型。如要瞭解支援的觸發條件、事件類型和相關聯的事件資料格式,請參閱「函式觸發條件」。

Google 事件存放區包含可用於處理 Google 發出的 CloudEvents 的資源。

函式終止

Cloud Run 會在函式傳回時,將事件驅動函式視為已完成執行。如果函式建立背景工作 (例如使用執行緒、未來、JavaScript Promise 物件、回呼或系統程序),您必須先終止或以其他方式解決這些工作,才能從函式返回。在函式傳回之前,未終止的任何工作可能不會完成,並可能導致未定義的行為。

自動重試

事件驅動函式可設定為自動重試失敗的叫用作業。詳情請參閱「重試事件驅動函式」。

後續步驟