Cloud Pub/Sub Tutorial

This simple tutorial demonstrates writing, deploying, and triggering a Background Cloud Function with a Cloud Pub/Sub trigger. To learn more about Cloud Pub/Sub, see the Cloud Pub/Sub documentation.

Objectives

Costs

This tutorial uses billable components of Cloud Platform, including:

  • Google Cloud Functions
  • Google Cloud 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. Faça login na sua Conta do Google.

    Se você ainda não tiver uma, inscreva-se.

  2. Selecione ou crie um projeto do GCP.

    Acessar a página Gerenciar recursos

  3. Verifique se o faturamento foi ativado para o projeto.

    Saiba como ativar o faturamento

  4. {% dynamic if "no_credentials" in setvar.task_params %}{% dynamic setvar credential_type %}NO_AUTH{% dynamic endsetvar %}{% dynamic if not setvar.redirect_url %}{% dynamic setvar redirect_url %}https://console.cloud.google.com{% dynamic endsetvar %}{% dynamic endif %}{% dynamic endif %}{% dynamic if setvar.in_henhouse_no_auth_whitelist %}{% dynamic if not setvar.credential_type %}{% dynamic setvar credential_type %}NO_AUTH{% dynamic endsetvar %}{% dynamic endif %}{% dynamic elif setvar.in_henhouse_service_account_whitelist %}{% dynamic if not setvar.credential_type %}{% dynamic setvar credential_type %}SERVICE_ACCOUNT{% dynamic endsetvar %}{% dynamic endif %}{% dynamic endif %}{% dynamic if not setvar.service_account_roles and setvar.credential_type == "SERVICE_ACCOUNT" %}{% dynamic setvar service_account_roles %}{% dynamic endsetvar %}{% dynamic endif %}{% dynamic setvar console %}{% dynamic if "no_steps" not in setvar.task_params %}
  5. {% dynamic endif %}{% dynamic if setvar.api_list %}{% dynamic if setvar.in_henhouse_no_auth_whitelist or setvar.in_henhouse_service_account_whitelist %} Configure um projeto do Console do GCP.

    Configurar um projeto

    Clique para:

    • criar ou selecionar um projeto;
    • ativar {% dynamic if setvar.api_names %}{% dynamic print setvar.api_names %}{% dynamic else %}obrigatória{% dynamic endif %}{% dynamic if "," in setvar.api_list %} APIs{% dynamic elif "API" in setvar.api_names %}{% dynamic else %} API{% dynamic endif %} para o projeto;
    • {% dynamic if setvar.credential_type == 'SERVICE_ACCOUNT' %}
    • criar uma conta de serviço;
    • fazer o download de uma chave privada como JSON.
    • {% dynamic endif %}

    É possível ver e gerenciar esses recursos a qualquer momento no Console do GCP.

    {% dynamic else %}{% dynamic if "no_text" not in setvar.task_params %} Ativar {% dynamic if setvar.api_names %}{% dynamic print setvar.api_names %}{% dynamic else %}obrigatória{% dynamic endif %}{% dynamic if "," in setvar.api_list %} APIs{% dynamic elif "API" in setvar.api_names %}{% dynamic else %} API{% dynamic endif %}. {% dynamic endif %}

    Ativar {% dynamic if "," in setvar.api_list %} as APIs{% dynamic else %} a API{% dynamic endif %}

    {% dynamic endif %}{% dynamic endif %}{% dynamic if "no_steps" not in setvar.task_params %}
  6. {% dynamic endif %}{% dynamic endsetvar %}{% dynamic print setvar.console %}
  7. Install and initialize the Cloud SDK.
  8. Update and install gcloud components:

    Node.js 8/10

    gcloud components update

    Node.js 6 (Deprecated)

    gcloud components update

    Python

    gcloud components update

    Go

    gcloud components update
  9. 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 Cloud Pub/Sub:

    Node.js 8/10

    cd nodejs-docs-samples/functions/node8/

    Node.js 6 (Deprecated)

    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 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 the function

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

Node.js 8

gcloud functions deploy helloPubSub --runtime nodejs8 --trigger-topic YOUR_TOPIC_NAME

Node.js 10 (Beta)

gcloud functions deploy helloPubSub --runtime nodejs10 --trigger-topic YOUR_TOPIC_NAME

Node.js 6 (Deprecated)

gcloud functions deploy helloPubSub --runtime nodejs6 --trigger-topic YOUR_TOPIC_NAME

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

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

Triggering the function

  1. Publish a message to your Cloud 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 Cloud 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
    

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. No Console do GCP, acesse a página "Projetos".

    Acessar a página Projetos

  2. Na lista de projetos, selecione um e clique em Excluir projeto.
  3. Na caixa de diálogo, digite o código do projeto e clique em Encerrar para excluí-lo.

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 Platform Console.

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…

Cloud Functions Documentation