Cloud Pub/Sub 튜토리얼(2세대)


이 튜토리얼에서는 Cloud Pub/Sub 트리거를 사용하여 이벤트 기반 Cloud 함수를 작성, 배포, 트리거하는 방법을 간략하게 설명합니다.

Pub/Sub를 처음 사용하는 경우 자세히 알아보려면 Pub/Sub 문서에서 특히 주제 및 구독 관리를 참조하세요. Cloud Functions에서 Pub/Sub 주제 및 구독 작업의 개요는 Google Cloud Pub/Sub 트리거를 참조하세요.

Pub/Sub 자체를 사용하는 코드 샘플을 찾고 있다면 Google Cloud 샘플 브라우저를 방문하세요.

목표

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

  • Cloud Functions
  • Cloud Build
  • Pub/Sub
  • Artifact Registry
  • Eventarc
  • Cloud Logging

자세한 내용은 Cloud Functions 가격 책정을 참조하세요.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. Google Cloud를 처음 사용하는 사용자는 무료 체험판을 사용할 수 있습니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub 사용 설정

    API 사용 설정

  5. Google Cloud CLI를 설치합니다.
  6. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  7. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  8. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  9. API Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub 사용 설정

    API 사용 설정

  10. Google Cloud CLI를 설치합니다.
  11. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  12. gcloud CLI가 이미 설치되어 있으면 다음 명령어를 실행하여 업데이트합니다.

    gcloud components update
  13. 개발 환경을 준비합니다.

기본 요건

Pub/Sub 주제를 만듭니다.

gcloud pubsub topics create YOUR_TOPIC_NAME

이 단계는 함수를 배포하기 전에 필수 단계입니다. Cloud Functions(2세대)에서는 함수를 배포할 때 Pub/Sub 주제가 자동으로 생성되지 않습니다.

애플리케이션 준비

  1. 샘플 앱 저장소를 로컬 머신에 클론합니다.

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

  2. Pub/Sub에 액세스하기 위한 Cloud Functions 샘플 코드가 있는 디렉터리로 변경합니다.

    Node.js

    cd nodejs-docs-samples/functions/v2/helloPubSub/

    Python

    cd python-docs-samples/functions/v2/pubsub/

    Go

    cd golang-samples/functions/functionsv2/hellopubsub/

    Java

    cd java-docs-samples/functions/v2/pubsub/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloPubSub/

    Ruby

    cd ruby-docs-samples/functions/helloworld/pubsub/

    PHP

    cd php-docs-samples/functions/helloworld_pubsub/

  3. 다음 샘플 코드를 살펴봅니다.

    Node.js

    const functions = require('@google-cloud/functions-framework');
    
    // Register a CloudEvent callback with the Functions Framework that will
    // be executed when the Pub/Sub trigger topic receives a message.
    functions.cloudEvent('helloPubSub', cloudEvent => {
      // The Pub/Sub message is passed as the CloudEvent's data payload.
      const base64name = cloudEvent.data.message.data;
    
      const name = base64name
        ? Buffer.from(base64name, 'base64').toString()
        : 'World';
    
      console.log(`Hello, ${name}!`);
    });

    Python

    import base64
    
    from cloudevents.http import CloudEvent
    import functions_framework
    
    # Triggered from a message on a Cloud Pub/Sub topic.
    @functions_framework.cloud_event
    def subscribe(cloud_event: CloudEvent) -> None:
        # Print out the data from Pub/Sub, to prove that it worked
        print(
            "Hello, " + base64.b64decode(cloud_event.data["message"]["data"]).decode() + "!"
        )
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"context"
    	"fmt"
    	"log"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    	"github.com/cloudevents/sdk-go/v2/event"
    )
    
    func init() {
    	functions.CloudEvent("HelloPubSub", helloPubSub)
    }
    
    // MessagePublishedData contains the full Pub/Sub message
    // See the documentation for more details:
    // https://cloud.google.com/eventarc/docs/cloudevents#pubsub
    type MessagePublishedData struct {
    	Message PubSubMessage
    }
    
    // PubSubMessage is the payload of a Pub/Sub event.
    // See the documentation for more details:
    // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
    type PubSubMessage struct {
    	Data []byte `json:"data"`
    }
    
    // helloPubSub consumes a CloudEvent message and extracts the Pub/Sub message.
    func helloPubSub(ctx context.Context, e event.Event) error {
    	var msg MessagePublishedData
    	if err := e.DataAs(&msg); err != nil {
    		return fmt.Errorf("event.DataAs: %w", err)
    	}
    
    	name := string(msg.Message.Data) // Automatically decoded from base64.
    	if name == "" {
    		name = "World"
    	}
    	log.Printf("Hello, %s!", name)
    	return nil
    }
    

    Java

    import com.google.cloud.functions.CloudEventsFunction;
    import com.google.gson.Gson;
    import functions.eventpojos.PubSubBody;
    import io.cloudevents.CloudEvent;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import java.util.logging.Logger;
    
    public class SubscribeToTopic implements CloudEventsFunction {
      private static final Logger logger = Logger.getLogger(SubscribeToTopic.class.getName());
    
      @Override
      public void accept(CloudEvent event) {
        // The Pub/Sub message is passed as the CloudEvent's data payload.
        if (event.getData() != null) {
          // Extract Cloud Event data and convert to PubSubBody
          String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
          Gson gson = new Gson();
          PubSubBody body = gson.fromJson(cloudEventData, PubSubBody.class);
          // Retrieve and decode PubSub message data
          String encodedData = body.getMessage().getData();
          String decodedData =
              new String(Base64.getDecoder().decode(encodedData), StandardCharsets.UTF_8);
          logger.info("Hello, " + decodedData + "!");
        }
      }
    }

    C#

    using CloudNative.CloudEvents;
    using Google.Cloud.Functions.Framework;
    using Google.Events.Protobuf.Cloud.PubSub.V1;
    using Microsoft.Extensions.Logging;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace HelloPubSub;
    
    public class Function : ICloudEventFunction<MessagePublishedData>
    {
        private readonly ILogger _logger;
    
        public Function(ILogger<Function> logger) =>
            _logger = logger;
    
        public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
        {
            string nameFromMessage = data.Message?.TextData;
            string name = string.IsNullOrEmpty(nameFromMessage) ? "world" : nameFromMessage;
            _logger.LogInformation("Hello {name}", name);
            return Task.CompletedTask;
        }
    }

    Ruby

    require "functions_framework"
    require "base64"
    
    FunctionsFramework.cloud_event "hello_pubsub" do |event|
      # The event parameter is a CloudEvents::Event::V1 object.
      # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
      name = Base64.decode64 event.data["message"]["data"] rescue "World"
    
      # A cloud_event function does not return a response, but you can log messages
      # or cause side effects such as sending additional events.
      logger.info "Hello, #{name}!"
    end

    PHP

    
    use CloudEvents\V1\CloudEventInterface;
    use Google\CloudFunctions\FunctionsFramework;
    
    // Register the function with Functions Framework.
    // This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment
    // variable when deploying. The `FUNCTION_TARGET` environment variable should
    // match the first parameter.
    FunctionsFramework::cloudEvent('helloworldPubsub', 'helloworldPubsub');
    
    function helloworldPubsub(CloudEventInterface $event): void
    {
        $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
    
        $cloudEventData = $event->getData();
        $pubSubData = base64_decode($cloudEventData['message']['data']);
    
        $name = $pubSubData ? htmlspecialchars($pubSubData) : 'World';
        fwrite($log, "Hello, $name!" . PHP_EOL);
    }

함수 배포

Pub/Sub 트리거를 사용하여 함수를 배포하려면 샘플 코드(또는 자바의 경우 pom.xml 파일)가 포함된 디렉터리에서 다음 명령어를 실행합니다.

Node.js

gcloud functions deploy nodejs-pubsub-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloPubSub \
--trigger-topic=YOUR_TOPIC_NAME

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

Python

gcloud functions deploy python-pubsub-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=subscribe \
--trigger-topic=YOUR_TOPIC_NAME

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

Go

gcloud functions deploy go-pubsub-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloPubSub \
--trigger-topic=YOUR_TOPIC_NAME

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

Java

gcloud functions deploy java-pubsub-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.SubscribeToTopic \
--memory=512MB \
--trigger-topic=YOUR_TOPIC_NAME

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

C#

gcloud functions deploy csharp-pubsub-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloPubSub.Function \
--trigger-topic=YOUR_TOPIC_NAME

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

Ruby

gcloud functions deploy ruby-pubsub-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_pubsub \
--trigger-topic=YOUR_TOPIC_NAME

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

PHP

gcloud functions deploy php-pubsub-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloworldPubsub \
--trigger-topic=YOUR_TOPIC_NAME

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

여기서 YOUR_TOPIC_NAME은 구독할 함수에 대한 Pub/Sub 주제 이름입니다.

Google Cloud 콘솔 또는 gcloud 명령줄 도구를 사용하여 deploy 명령어를 실행하기 전 주제를 만들어야 합니다. Cloud Functions(1세대)와 달리 Cloud Functions(2세대)에서는 Pub/Sub 트리거로 함수를 배포할 때 Pub/Sub 주제가 자동으로 생성되지 않습니다.

함수 트리거

Pub/Sub 함수를 테스트하려면 다음 안내를 따르세요.

  1. 주제에 메시지 게시하기

    gcloud pubsub topics publish my-topic --message="Friend"
    
  2. 함수 로그를 읽어 결과를 확인합니다.

    gcloud functions logs read \
      --gen2 \
      --region=REGION \
      --limit=5 \
      FUNCTION_NAME
    

    다음을 바꿉니다.

    • REGION은 함수를 배포한 Google Cloud 리전의 이름입니다(예: us-west1).
    • FUNCTION_NAME은 함수를 배포할 때 지정한 이름입니다. 예를 들어 이 튜토리얼의 Node.js 함수nodejs-pubsub-function 함수 이름으로 배포되었습니다.

    새 '친구' 메시지가 포함된 로깅 출력을 볼 수 있습니다.

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

프로젝트 삭제

비용이 청구되지 않도록 하는 가장 쉬운 방법은 튜토리얼에서 만든 프로젝트를 삭제하는 것입니다.

프로젝트를 삭제하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

Cloud 함수 삭제

Cloud Functions를 삭제해도 Cloud Storage에 저장된 리소스는 삭제되지 않습니다.

이 튜토리얼에서 만든 Cloud Function을 삭제하려면 다음 명령어를 실행합니다.

Node.js

gcloud functions delete nodejs-pubsub-function --gen2 --region REGION 

Python

gcloud functions delete python-pubsub-function --gen2 --region REGION 

Go

gcloud functions delete go-pubsub-function --gen2 --region REGION 

Java

gcloud functions delete java-pubsub-function --gen2 --region REGION 

C#

gcloud functions delete csharp-pubsub-function --gen2 --region REGION 

Ruby

gcloud functions delete ruby-pubsub-function --gen2 --region REGION 

PHP

gcloud functions delete php-pubsub-function --gen2 --region REGION 

Google Cloud 콘솔에서 Cloud Functions를 삭제할 수도 있습니다.