.NET 语言

您可以使用不同的 .NET 语言(C#、Visual Basic 或 F#)编写函数。所有语言的核心任务都相同 - 您创建一个实现某个 Functions 框架接口的类:

本文档提供了 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

如需查看 F# 和 Visual Basic 示例,请参阅 .NET 语言

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 --entry-point HelloWorldFSharp.Function --runtime dotnet6 --trigger-http --allow-unauthenticated

Visual Basic

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

CloudEvent 示例

如果您要在响应异步事件(例如 Pub/Sub 主题中收到消息、Cloud Storage 存储分区发生更改或 Firebase 事件)时间接调用 Cloud Functions 函数,则可以使用 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 --entry-point HelloPubSubFSharp.Function --runtime dotnet6 --trigger-topic my-topic --allow-unauthenticated

Visual Basic

gcloud functions deploy vb-hello-pubsub --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'