Google Cloud Pub/Sub Triggers

Cloud Functions can be triggered by messages published to Cloud Pub/Sub topics in the same GCP project as the function. Cloud Pub/Sub is a globally distributed message bus that automatically scales as you need it and provides a foundation for building your own robust, global services.

Event types

There is a single Cloud Pub/Sub event used by Cloud Functions, and it has the trigger type value google.pubsub.topic.publish.

This event is sent when a message is published to a Cloud Pub/Sub topic that is specified when a function is deployed. Every message published to this topic will trigger function execution with message contents passed as input data.

Event structure

Cloud Functions triggered from a Cloud Pub/Sub topic will be sent events conforming to the PubsubMessage type, with the caveat that publishTime and messageId are not directly available in the PubsubMessage. Instead, you can access publishTime and messageId via the event ID and timestamp properties of the event metadata. This metadata is accessible via the context object that is passed to your function when it is invoked.

The payload of the PubsubMessage object, the data published to the topic, is stored as a base64-encoded string in the data attribute of the PubsubMessage. To extract the payload of the PubsubMessage object, you may need to decode the data attribute as shown in the examples below.

Sample code

Node.js 8/10

/**
 * 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} pubSubEvent The event payload.
 * @param {object} context The event metadata.
 */
exports.helloPubSub = (pubSubEvent, context) => {
  const name = pubSubEvent.data
    ? Buffer.from(pubSubEvent.data, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);
};

Node.js 6 (Deprecated)

/**
 * 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} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloPubSub = (event, callback) => {
  const pubsubMessage = event.data;
  const name = pubsubMessage.data
    ? Buffer.from(pubsubMessage.data, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);

  callback();
};

Python

def hello_pubsub(data, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         data (dict): The dictionary with data specific to this type of event.
         context (google.cloud.functions.Context): The Cloud Functions event
         metadata.
    """
    import base64

    if 'data' in data:
        name = base64.b64decode(data['data']).decode('utf-8')
    else:
        name = 'World'
    print('Hello {}!'.format(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.
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)
	if name == "" {
		name = "World"
	}
	log.Printf("Hello, %s!", name)
	return nil
}

Deploying your function

The following gcloud command deploys a function that will be triggered when a message is published to a Cloud Pub/Sub topic:

Node.js 8

gcloud functions deploy FUNCTION_NAME --runtime nodejs8 --trigger-topic TOPIC_NAME

Node.js 10 (Beta)

gcloud functions deploy FUNCTION_NAME --runtime nodejs10 --trigger-topic TOPIC_NAME

Node.js 6 (Deprecated)

gcloud functions deploy FUNCTION_NAME --runtime nodejs6 --trigger-topic TOPIC_NAME

Python

gcloud functions deploy FUNCTION_NAME --runtime python37 --trigger-topic TOPIC_NAME

Go

gcloud functions deploy FUNCTION_NAME --runtime go111 --trigger-topic TOPIC_NAME

where FUNCTION_NAME is the name of the function and TOPIC_NAME is the name of the Cloud Pub/Sub topic to which the function will be subscribed. If the topic doesn't exist, it is created during deployment.

See the Cloud Pub/Sub Tutorial for a complete example of how to use Cloud Pub/Sub triggers.

Legacy Cloud Pub/Sub triggers

The gcloud command below deploys a function that is triggered by legacy Cloud Pub/Sub notifications on a specific topic. These notifications are supported for legacy functions already consuming these events. However, we recommend using the --trigger-topic flag instead, as the legacy notifications might be removed at a future date.

Node.js 8

gcloud functions deploy FUNCTION_NAME --runtime nodejs8 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Node.js 10 (Beta)

gcloud functions deploy FUNCTION_NAME --runtime nodejs10 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Node.js 6 (Deprecated)

gcloud functions deploy FUNCTION_NAME --runtime nodejs6 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Python

gcloud functions deploy FUNCTION_NAME --runtime python37 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Go

gcloud functions deploy FUNCTION_NAME --runtime go111 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Next steps

See the Cloud Pub/Sub Tutorial for an example of how to implement a background function that is triggered by Cloud Pub/Sub.

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Functions Documentation