Cloud Pub/Sub Tutorial

This simple tutorial demonstrates writing, deploying, and triggering a Background Cloud Function with a Cloud Pub/Sub trigger.

If you are new to Pub/Sub and want to learn more, see the Pub/Sub documentation, particularly managing topics and subscriptions. See Google Cloud Pub/Sub Triggers for an overview of working with Pub/Sub topics and subscriptions in Cloud Functions.

Objectives

Costs

This tutorial uses billable components of Cloud Platform, including:

  • Cloud Functions
  • Pub/Sub

Use the Pricing Calculator to generate a cost estimate based on your projected usage.

New Cloud Platform users might be eligible for a free trial.

Before you begin

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. In the Cloud Console, on the project selector page, select or create a Cloud project.

    Go to the project selector page

  3. Zorg dat facturering is ingeschakeld voor uw project.

    Meer informatie over het inschakelen van facturering

  4. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Enable the APIs

  5. Install and initialize the Cloud SDK.
  6. Update gcloud components:
    gcloud components update
  7. Prepare your development environment.

Preparing the application

  1. Clone the sample app repository to your local machine:

    Node.js

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

    Alternatively, you can download the sample as a zip file and extract it.

    Python

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

    Alternatively, you can download the sample as a zip file and extract it.

    Go

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

    Alternatively, you can download the sample as a zip file and extract it.

  2. Change to the directory that contains the Cloud Functions sample code for accessing Pub/Sub:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

  3. Take a look at the sample code:

    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} data The event payload.
     * @param {object} context The event metadata.
     */
    exports.helloPubSub = (data, context) => {
      const pubSubMessage = data;
      const name = pubSubMessage.data
        ? Buffer.from(pubSubMessage.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 `data` field contains the PubsubMessage message. The
             `attributes` field will contain custom attributes if there are any.
             context (google.cloud.functions.Context): The Cloud Functions event
             metadata. The `event_id` field contains the Pub/Sub message ID. The
             `timestamp` field contains the publish time.
        """
        import base64
    
        print("""This Function was triggered by messageId {} published at {}
        """.format(context.event_id, context.timestamp))
    
        if 'data' in event:
            name = base64.b64decode(event['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 the function

To deploy the function with a Pub/Sub trigger, run the following command in the directory where the sample code is located:

Node.js

gcloud functions deploy helloPubSub --runtime nodejs8 --trigger-topic YOUR_TOPIC_NAME
You can use the following values for the --runtime flag to specify your preferred Node.js version:
  • nodejs6 (deprecated)
  • nodejs8
  • nodejs10 (beta)

Python

gcloud functions deploy hello_pubsub --runtime python37 --trigger-topic YOUR_TOPIC_NAME

Go

gcloud functions deploy HelloPubSub --runtime go111 --trigger-topic YOUR_TOPIC_NAME
You can use the following values for the --runtime flag to specify your preferred Go version:
  • go111
  • go113 (beta)

where YOUR_TOPIC_NAME is the name of the Pub/Sub topic to which the function will be subscribed.

If YOUR_TOPIC_NAME doesn't already exist, this command creates it for you. You can also create a topic before you run the deploy command, using either the Cloud Console or the following gcloud command:

gcloud pubsub topics create YOUR_TOPIC_NAME

Triggering the function

  1. Publish a message to your Pub/Sub topic. In this example, the message is a name that the function will include in a greeting:

    gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

    Replace YOUR_TOPIC_NAME with the name of your Pub/Sub topic, and YOUR_NAME with an arbitrary string.

  2. Check the logs to be sure the executions have completed:

    gcloud functions logs read --limit 50
    

You can also publish a message to a Pub/Sub topic from within a function.

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

Deleting the project

The easiest way to eliminate billing is to delete the project that you created for the tutorial.

To delete the project:

  1. In the Cloud Console, go to the Manage resources page.

    Go to the Manage resources page

  2. In the project list, select the project that you want to delete and then click Delete .
  3. In the dialog, type the project ID and then click Shut down to delete the project.

Deleting the Cloud Function

Deleting Cloud Functions does not remove any resources stored in Cloud Storage.

To delete the Cloud Function you created in this tutorial, run the following command:

Node.js

gcloud functions delete helloPubSub 

Python

gcloud functions delete hello_pubsub 

Go

gcloud functions delete HelloPubSub 

You can also delete Cloud Functions from the Google Cloud Console.