Mit dem Pub/Sub-Emulator lokal testen

Sie können Funktionen lokal testen, bevor Sie sie bereitstellen. Verwenden Sie dazu Functions Framework in Verbindung mit dem Pub/Sub-Emulator. In den Beispielen auf dieser Seite wird Cloud Functions (2. Generation) verwendet.

Functions Framework mit Pub/Sub Emulator verwenden

Sie können eine Funktion lokal mit einer Push-Nachricht aus dem Pub/Sub-Emulator auslösen.

Testen Sie dieses Feature wie hier beschrieben. Beachten Sie, dass Sie drei separate Terminalinstanzen verwenden müssen:

  1. Prüfen Sie, ob das pack-Tool und Docker installiert sind.

  2. Starten Sie im ersten Terminal den Pub/Sub-Emulator auf Port 8043 in einem lokalen Projekt:

    gcloud beta emulators pubsub start \
        --project=abc \
        --host-port='localhost:8043'
    
  3. Erstellen Sie im zweiten Terminal ein Pub/Sub-Thema und -Abo:

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

    Verwenden Sie http://localhost:8080 als Endpunkt des Push-Abos.

    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. Klonen Sie im dritten Terminal das Beispiel-Repository auf Ihren lokalen Computer:

    Node.js

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

    Sie können auch das Beispiel als ZIP-Datei herunterladen und extrahieren.

    Python

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

    Sie können auch das Beispiel als ZIP-Datei herunterladen und extrahieren.

    Einfach loslegen (Go)

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

    Sie können auch das Beispiel als ZIP-Datei herunterladen und extrahieren.

    Wechseln Sie in das Verzeichnis, das den Cloud Functions-Beispielcode enthält:

    Node.js

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

    Python

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

    Go

    cd golang-samples/functions/functionsv2/hellopubsub/

    Sehen Sie sich den Beispielcode an:

    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() + "!"
        )
    
    

    Einfach loslegen (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
    }
    

    Erstellen Sie den Buildpack (dies kann einige Minuten dauern):

    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
    

    Einfach loslegen (Go)

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

    Starten Sie die Pub/Sub-Funktion auf Port 8080. Der Emulator sendet Push-Nachrichten:

    docker run --rm -p 8080:8080 my-function
    
  5. Rufen Sie die Funktion im zweiten Terminal auf, indem Sie eine Nachricht veröffentlichen. Die Nachrichtendaten müssen in base64 codiert sein. In diesem Beispiel wird der base64-codierte String {"foo":"bar"} verwendet.

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

    Die Funktionsausgabe sollte im dritten Terminal angezeigt werden.

    Drücken Sie zum Abbrechen Ctrl+C.