Linguaggi .NET

È possibile scrivere la funzione in diversi linguaggi .NET (C#, Visual Basic o F#). L'attività principale è la stessa in tutti i linguaggi: crei una classe che implementa una delle interfacce del framework di Functions:

Questo documento fornisce esempi per F# e Visual Basic.

Modelli

Tieni presente che per eseguire gli esempi in questo documento, utilizzerai i modelli:

  1. Installa l'SDK.NET.

  2. Installa il pacchetto del modello:

    dotnet new install Google.Cloud.Functions.Templates
    

I modelli vengono forniti per i tre tipi di funzioni in C# (valore predefinito), F# e Visual Basic. Quando crei un nuovo progetto da un modello, specifica -lang f# per creare un progetto F# o -lang vb per creare un progetto Visual Basic. Ad esempio, per creare una nuova funzione CloudEvent non digitata per Visual Basic, devi eseguire:

dotnet new gcf-untyped-event -lang vb

Per esempi di F# e Visual Basic, vedi Linguaggi.NET.

Esempi di funzioni HTTP

Puoi utilizzare le funzioni HTTP quando vuoi richiamare la tua funzione tramite una richiesta HTTP(S). I seguenti esempi restituiscono il messaggio "Hello World!"

Fa n.

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 :> _

Visiva

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

File di progetto per esempi HTTP

Ecco i file di progetto per gli esempi precedenti:

Fa n.

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

Visiva

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

Deployment delle funzioni HTTP

Fa n.

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

Visiva

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

Esempi di CloudEvent

Puoi utilizzare le funzioni CloudEvent quando vuoi che la funzione Cloud Function venga richiamata indirettamente in risposta a un evento asincrono, come un messaggio su un argomento Pub/Sub, una modifica in un bucket Cloud Storage o un evento Firebase.

Fa n.

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

Visiva

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

Deployment delle funzioni CloudEvent

Fa n.

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

Visiva

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

Testa gli esempi CloudEvent

Puoi testare gli esempi di CloudEvent come segue:

  1. Pubblica un messaggio nel tuo argomento Pub/Sub per attivare la funzione:

    gcloud pubsub topics publish my-topic --message Flurry
  2. Esamina i log:

    gcloud functions logs read --limit 10

Il risultato dovrebbe essere simile al seguente, con un messaggio che include il nome che hai pubblicato nell'argomento 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'