.NET 語言

您可以使用不同的 .NET 語言 (C#、Visual Basic 或 F#) 編寫函式。所有語言的核心工作都相同,您需要建立一個實作其中一個 Functions Framework 介面的類別:

本文件提供 F# 和 Visual Basic 的範例。

範本

請注意,如要執行本文件中的範例,您必須使用範本

  1. 安裝 .NET SDK

  2. 安裝範本套件:

    dotnet new install Google.Cloud.Functions.Templates
    

範本適用於 C# (預設)、F# 和 Visual Basic 中的三種函式。使用範本建立新專案時,請指定 -lang f# 建立 F# 專案,或指定 -lang vb 建立 Visual Basic 專案。舉例來說,如要為 Visual Basic 建立新的未指定類型的 CloudEvent 函式,請執行以下指令:

dotnet new gcf-untyped-event -lang vb

HTTP 函式範例

如要透過 HTTP(S) 要求叫用函式,請使用 HTTP 函式。以下範例會輸出訊息 "Hello World!"

F#

namespace HelloWorldFSharp

open Google.Cloud.Functions.Framework
open Microsoft.AspNetCore.Http

type Function() =
    interface IHttpFunction with
        member this.HandleAsync context =
            async {
                do! context.Response.WriteAsync "Hello World!" |> Async.AwaitTask
            } |> Async.StartAsTask :> _

Visual Basic

Imports Google.Cloud.Functions.Framework
Imports Microsoft.AspNetCore.Http

Public Class CloudFunction
    Implements IHttpFunction

    Public Async Function HandleAsync(context As HttpContext) As Task Implements IHttpFunction.HandleAsync
        Await context.Response.WriteAsync("Hello World!")
    End Function
End Class

HTTP 範例的專案檔案

以下是上述範例的專案檔案:

F#

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Function.fs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Google.Cloud.Functions.Hosting" Version="2.2.1" />
  </ItemGroup>
</Project>

Visual Basic

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <RootNamespace>HelloWorldVb</RootNamespace>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Google.Cloud.Functions.Hosting" Version="2.2.1" />
  </ItemGroup>
</Project>

部署 HTTP 函式

F#

 gcloud functions deploy fsharp-helloworld --no-gen2 --entry-point HelloWorldFSharp.Function --runtime dotnet6 --trigger-http --allow-unauthenticated

Visual Basic

 gcloud functions deploy vb-helloworld --no-gen2 --entry-point HelloWorldVb.CloudFunction --runtime dotnet6 --trigger-http --allow-unauthenticated

CloudEvent 範例

如要間接叫用 Cloud Run 函式來回應非同步事件 (例如 Pub/Sub 主題的訊息、Cloud Storage 儲存桶的變更或 Firebase 事件),請使用 CloudEvent 函式

F#

namespace HelloPubSubFSharp

open Google.Cloud.Functions.Framework
open Google.Events.Protobuf.Cloud.PubSub.V1
open Microsoft.Extensions.Logging
open System
open System.Threading.Tasks

type Function(logger: ILogger<Function>) =
    interface ICloudEventFunction<MessagePublishedData> with
        member this.HandleAsync(cloudEvent, data, cancellationToken) =
            let nameFromMessage = data.Message.TextData
            let name = if String.IsNullOrEmpty(nameFromMessage) then "world" else nameFromMessage
            logger.LogInformation("Hello {name}", name)
            Task.CompletedTask

Visual Basic

Imports System.Threading
Imports CloudNative.CloudEvents
Imports Google.Cloud.Functions.Framework
Imports Google.Events.Protobuf.Cloud.PubSub.V1
Imports Microsoft.Extensions.Logging

Public Class CloudFunction
    Implements ICloudEventFunction(Of MessagePublishedData)

    Private _logger As ILogger

    Public Sub New(ByVal logger As ILogger(Of CloudFunction))
        _logger = logger
    End Sub


    Public Function HandleAsync(cloudEvent As CloudEvent, data As MessagePublishedData, cancellationToken As CancellationToken) As Task _
        Implements ICloudEventFunction(Of MessagePublishedData).HandleAsync

        Dim nameFromMessage = data.Message?.TextData
        Dim name = If(String.IsNullOrEmpty(nameFromMessage), "world", nameFromMessage)
        _logger.LogInformation("Hello {name}", name)

        Return Task.CompletedTask
    End Function
End Class

部署 CloudEvent 函式

F#

 gcloud functions deploy fsharp-hello-pubsub --no-gen2 --entry-point HelloPubSubFSharp.Function --runtime dotnet6 --trigger-topic my-topic --allow-unauthenticated

Visual Basic

 gcloud functions deploy vb-hello-pubsub --no-gen2 --entry-point HelloPubSubVb.CloudFunction --runtime dotnet6 --trigger-topic my-topic --allow-unauthenticated

測試 CloudEvent 範例

您可以按照下列步驟測試 CloudEvent 範例:

  1. 將訊息發布至 Pub/Sub 主題,藉此觸發函式:

    gcloud pubsub topics publish my-topic --message Flurry
  2. 查看記錄:

    gcloud functions logs read --limit 10

畫面上應會顯示類似以下內容,其中包含您發布至 Pub/Sub 主題的名稱:

D      my-function  ...  Function execution started
I      my-function  ...  Hello Flurry!
D      my-function  ...  Function execution took 39 ms, finished with status: 'ok'