Cloud Pub/Sub 튜토리얼 1세대


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

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

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

목표

비용

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

  • Cloud Functions
  • Pub/Sub

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

시작하기 전에

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

    프로젝트 선택기로 이동

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

  4. API Cloud Functions and Cloud 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 and Cloud Pub/Sub 사용 설정

    API 사용 설정

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

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

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

애플리케이션 준비

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

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/hello-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

    /**
     * Background Cloud Function to be triggered by Pub/Sub.
     * This function is exported by index.js, and executed when
     * the trigger topic receives a message.
     *
     * @param {object} message The Pub/Sub message.
     * @param {object} context The event metadata.
     */
    exports.helloPubSub = (message, context) => {
      const name = message.data
        ? Buffer.from(message.data, 'base64').toString()
        : 'World';
    
      console.log(`Hello, ${name}!`);
    };

    Python

    def hello_pubsub(event, context):
        """Background Cloud Function to be triggered by Pub/Sub.
        Args:
             event (dict):  The dictionary with data specific to this type of
                            event. The `@type` field maps to
                             `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                            The `data` field maps to the PubsubMessage data
                            in a base64-encoded string. The `attributes` field maps
                            to the PubsubMessage attributes if any is present.
             context (google.cloud.functions.Context): Metadata of triggering event
                            including `event_id` which maps to the PubsubMessage
                            messageId, `timestamp` which maps to the PubsubMessage
                            publishTime, `event_type` which maps to
                            `google.pubsub.topic.publish`, and `resource` which is
                            a dictionary that describes the service API endpoint
                            pubsub.googleapis.com, the triggering topic's name, and
                            the triggering event type
                            `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
        Returns:
            None. The output is written to Cloud Logging.
        """
        import base64
    
        print(
            """This Function was triggered by messageId {} published at {} to {}
        """.format(
                context.event_id, context.timestamp, context.resource["name"]
            )
        )
    
        if "data" in event:
            name = base64.b64decode(event["data"]).decode("utf-8")
        else:
            name = "World"
        print(f"Hello {name}!")
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"context"
    	"log"
    )
    
    // 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 Pub/Sub message.
    func HelloPubSub(ctx context.Context, m PubSubMessage) error {
    	name := string(m.Data) // Automatically decoded from base64.
    	if name == "" {
    		name = "World"
    	}
    	log.Printf("Hello, %s!", name)
    	return nil
    }
    

    Java

    
    import com.google.cloud.functions.BackgroundFunction;
    import com.google.cloud.functions.Context;
    import functions.eventpojos.PubsubMessage;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class HelloPubSub implements BackgroundFunction<PubsubMessage> {
      private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());
    
      @Override
      public void accept(PubsubMessage message, Context context) {
        String name = "world";
        if (message != null && message.getData() != null) {
          name = new String(
              Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
              StandardCharsets.UTF_8);
        }
        logger.info(String.format("Hello %s!", name));
        return;
      }
    }

    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 helloPubSub \
--runtime nodejs20 \
--trigger-topic YOUR_TOPIC_NAME

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

Python

gcloud functions deploy hello_pubsub \
--runtime python312 \
--trigger-topic YOUR_TOPIC_NAME

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

Go

gcloud functions deploy HelloPubSub \
--runtime go121 \
--trigger-topic YOUR_TOPIC_NAME

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

Java

gcloud functions deploy java-pubsub-function \
--entry-point functions.HelloPubSub \
--runtime java17 \
--memory 512MB \
--trigger-topic YOUR_TOPIC_NAME

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

C#

gcloud functions deploy csharp-pubsub-function \
--entry-point HelloPubSub.Function \
--runtime dotnet6 \
--trigger-topic YOUR_TOPIC_NAME

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

Ruby

gcloud functions deploy hello_pubsub --runtime ruby32 \
--trigger-topic YOUR_TOPIC_NAME

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

PHP

 gcloud functions deploy helloworldPubsub --runtime php82 \
--trigger-topic YOUR_TOPIC_NAME

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

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

YOUR_TOPIC_NAME이 아직 없으면 이 명령어가 자동으로 생성됩니다. deploy 명령어를 실행하기 전에 Google Cloud 콘솔 또는 다음 gcloud 명령어를 사용하여 주제를 만들 수도 있습니다.

gcloud pubsub topics create YOUR_TOPIC_NAME

함수 트리거

  1. 메시지를 Pub/Sub 주제에 게시합니다. 이 예시에서 함수가 인사말에 포함할 이름이 메시지입니다.

    gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

    YOUR_TOPIC_NAME을 Cloud Pub/Sub 주제의 이름으로 바꾸고 YOUR_NAME은 임의의 문자열로 바꿉니다.

  2. 로그를 통해 실행이 완료되었는지 확인합니다.

    gcloud functions logs read --limit 50
    

함수 내에서 Pub/Sub 주제에 메시지를 게시할 수도 있습니다.

삭제

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

프로젝트 삭제

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

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

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

    리소스 관리로 이동

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

Cloud 함수 삭제

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

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

Node.js

gcloud functions delete helloPubSub 

Python

gcloud functions delete hello_pubsub 

Go

gcloud functions delete HelloPubSub 

Java

gcloud functions delete java-pubsub-function 

C#

gcloud functions delete csharp-pubsub-function 

Ruby

gcloud functions delete hello_pubsub 

PHP

gcloud functions delete helloworldPubsub 

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