.NET 언어

다양한 .NET 언어(C#, Visual Basic, F#)를 사용하여 함수를 작성할 수도 있습니다. 핵심 작업은 모든 언어가 동일합니다. 즉, 함수 프레임워크 인터페이스 중 하나를 구현하는 클래스를 만드는 것입니다.

이 문서에서는 F# 및 Visual Basic을 예로 들어 설명합니다.

템플릿

이 문서의 예시를 실행하려면 템플릿을 사용합니다.

  1. .NET SDK를 설치합니다.

  2. 템플릿 패키지를 설치합니다.

    dotnet new install Google.Cloud.Functions.Templates
    

C#(기본값), F#, Visual Basic과 같은 3가지 함수 유형의 템플릿이 제공됩니다. 템플릿에서 새 프로젝트를 만들 때는 -lang f#을 지정하여 F# 프로젝트를 만들거나 -lang vb를 지정하여 Visual Basic 프로젝트를 만듭니다. 예를 들어 유형화되지 않은 Visual Basic용 CloudEvent 함수를 새로 만들려면 다음을 실행합니다.

dotnet new gcf-untyped-event -lang vb

F# 및 Visual Basic의 예시는 .NET 언어를 참조하세요.

HTTP 함수 예시

HTTP 요청을 통해 함수를 호출하려면 HTTP 함수를 사용합니다. 다음 예시는 "Hello World!" 메시지를 출력합니다.

F#Visual Basic
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 :> _
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#Visual Basic
<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>
<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#Visual Basic
gcloud functions deploy fsharp-helloworld --entry-point HelloWorldFSharp.Function --runtime dotnet8 --trigger-http --allow-unauthenticated
gcloud functions deploy vb-helloworld --entry-point HelloWorldVb.CloudFunction --runtime dotnet8 --trigger-http --allow-unauthenticated

CloudEvent 예시

Pub/Sub 주제의 메시지, Cloud Storage 버킷의 변경사항 또는 Firebase 이벤트와 같은 비동기 이벤트에 대한 응답으로 Cloud Run 함수를 간접적으로 호출하려면 CloudEvent 함수를 사용합니다.

F#Visual Basic
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
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#Visual Basic
gcloud functions deploy fsharp-hello-pubsub --entry-point HelloPubSubFSharp.Function --runtime dotnet8 --trigger-topic my-topic --allow-unauthenticated
gcloud functions deploy vb-hello-pubsub --entry-point HelloPubSubVb.CloudFunction --runtime dotnet8 --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'