Lenguajes .NET
Puedes escribir tu función en diferentes lenguajes de .NET (C#, Visual Basic o F#). La tarea principal es la misma en todos los lenguajes: crear una clase que implemente una de las interfaces de Functions Framework:
IHttpFunction
- El
ICloudEvent<T>
genérico - El
ICloudEvent
no genérico
En este documento se proporcionan ejemplos de F# y Visual Basic.
Plantillas
Ten en cuenta que, para ejecutar los ejemplos de este documento, utilizarás las plantillas:
Instala el SDK de.NET.
Instala el paquete de plantilla:
dotnet new install Google.Cloud.Functions.Templates
Se proporcionan plantillas para los tres tipos de funciones en C# (el valor predeterminado), F# y Visual Basic. Al crear un proyecto a partir de una plantilla, especifica -lang f#
para crear un proyecto de F# o -lang vb
para crear un proyecto de Visual Basic. Por ejemplo, para crear una función CloudEvent sin tipo para Visual Basic, ejecutarías lo siguiente:
dotnet new gcf-untyped-event -lang vb
Ejemplos de funciones HTTP
Las funciones HTTP se usan cuando quieres invocar tu función mediante una solicitud HTTP(S). En los siguientes ejemplos se muestra el mensaje
"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
Archivos de proyecto de ejemplos de HTTP
Estos son los archivos de proyecto de los ejemplos anteriores:
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>
Desplegar las funciones 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
Ejemplos de CloudEvent
Usa funciones de CloudEvents cuando quieras que tu función de Cloud Run se invoque indirectamente en respuesta a un evento asíncrono, como un mensaje en un tema de Pub/Sub, un cambio en un segmento de Cloud Storage o un evento de Firebase.
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
Desplegar las funciones de 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
Probar los ejemplos de CloudEvent
Para probar los ejemplos de CloudEvents, sigue estos pasos:
Publica un mensaje en tu tema de Pub/Sub para activar la función:
gcloud pubsub topics publish my-topic --message Flurry
Consulta los registros:
gcloud functions logs read --limit 10
Debería ver algo parecido a esto, con un mensaje que incluya el nombre que ha publicado en el tema de 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'