Pub/Sub 에뮬레이터로 로컬에서 테스트

함수를 배포하기 전에 Pub/Sub 에뮬레이터와 함께 함수 프레임워크를 사용하여 함수를 로컬에서 테스트할 수 있습니다. 이 페이지의 예시에서는 Cloud Functions(2세대)를 사용합니다.

Pub/Sub 에뮬레이터에 함수 프레임워크 사용

Pub/Sub 에뮬레이터의 푸시 메시지를 사용하여 함수를 로컬로 트리거할 수 있습니다.

여기에 설명된 대로 이 기능을 테스트합니다. 3개의 개별 터미널 인스턴스를 사용해야 합니다.

  1. pack 도구Docker가 설치되어 있는지 확인하세요.

  2. 첫 번째 터미널에서는 로컬 프로젝트에서 포트 8043으로 Pub/Sub 에뮬레이터를 시작합니다.

    gcloud beta emulators pubsub start \
        --project=abc \
        --host-port='localhost:8043'
    
  3. 두 번째 터미널에서는 Pub/Sub 주제 및 구독을 만듭니다.

    curl -s -X PUT 'http://localhost:8043/v1/projects/abc/topics/mytopic'
    

    http://localhost:8080을 푸시 구독의 엔드포인트로 사용하세요.

    curl -s -X PUT 'http://localhost:8043/v1/projects/abc/subscriptions/mysub' \
        -H 'Content-Type: application/json' \
        --data '{"topic":"projects/abc/topics/mytopic","pushConfig":{"pushEndpoint":"http://localhost:8080/projects/abc/topics/mytopic"}}'
    
  4. 세 번째 터미널에서는 샘플 저장소를 로컬 머신에 클론합니다.

    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 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    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/

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

    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
    }
    

    빌드 팩을 만듭니다. 몇 분 정도 걸릴 수 있습니다.

    Node.js

    pack build \
      --builder gcr.io/buildpacks/builder:v1 \
      --env GOOGLE_FUNCTION_SIGNATURE_TYPE=event \
      --env GOOGLE_FUNCTION_TARGET=helloPubSub \
      my-function
    

    Python

    pack build \
      --builder gcr.io/buildpacks/builder:v1 \
      --env GOOGLE_FUNCTION_SIGNATURE_TYPE=event \
      --env GOOGLE_FUNCTION_TARGET=subscribe \
      my-function
    

    Go

    pack build \
      --builder gcr.io/buildpacks/builder:v1 \
      --env GOOGLE_FUNCTION_SIGNATURE_TYPE=event \
      --env GOOGLE_FUNCTION_TARGET=HelloPubSub \
      my-function
    

    포트 8080에서 Pub/Sub 함수를 시작합니다. 여기에서 에뮬레이터가 푸시 메시지를 전송합니다.

    docker run --rm -p 8080:8080 my-function
    
  5. 두 번째 터미널에서 메시지를 게시하여 함수를 호출합니다. 메시지 데이터는 base64로 인코딩되어야 합니다. 이 예시에서는 base64로 인코딩된 문자열 {"foo":"bar"}을 사용합니다.

    curl -s -X POST 'http://localhost:8043/v1/projects/abc/topics/mytopic:publish' \
        -H 'Content-Type: application/json' \
        --data '{"messages":[{"data":"eyJmb28iOiJiYXIifQ=="}]}'
    

    세 번째 터미널에 함수 출력이 표시됩니다.

    취소하려면 Ctrl+C를 누르세요.