Tutorial de Cloud Pub/Sub (1.ª gen.)


En este sencillo tutorial se muestra cómo escribir, desplegar y activar una función de Cloud Run basada en eventos con un activador de Pub/Sub.

Si no conoces Pub/Sub y quieres obtener más información, consulta la documentación de Pub/Sub, en concreto la sección sobre gestión de temas y suscripciones. Consulta Activadores de Pub/Sub para obtener una descripción general de cómo trabajar con temas y suscripciones de Pub/Sub en funciones de Cloud Run.

Si buscas ejemplos de código para usar Pub/Sub, visita el explorador de ejemplos.

Objetivos

Costes

En este documento, se utilizan los siguientes componentes facturables de Google Cloud:

  • Cloud Run functions
  • Pub/Sub

Para generar una estimación de costes basada en el uso previsto, utiliza la calculadora de precios.

Los usuarios nuevos Google Cloud pueden disfrutar de una prueba gratuita.

Antes de empezar

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  7. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  13. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  14. Si ya tienes instalada la CLI de gcloud, actualízala ejecutando el siguiente comando:

    gcloud components update
  15. Prepara tu entorno de desarrollo.
  16. Preparar la aplicación

    1. Clona el repositorio de aplicaciones de muestra en la máquina local:

      Node.js

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

      También puedes descargar el ejemplo como un archivo ZIP y extraerlo.

      Python

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

      También puedes descargar el ejemplo como un archivo ZIP y extraerlo.

      Go

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

      También puedes descargar el ejemplo como un archivo ZIP y extraerlo.

      Java

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

      También puedes descargar el ejemplo como un archivo ZIP y extraerlo.

      Ruby

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

      También puedes descargar el ejemplo como un archivo ZIP y extraerlo.

    2. Cambia al directorio que contiene el código de ejemplo de las funciones de Cloud Run para acceder a Pub/Sub:

      Node.js

      cd nodejs-docs-samples/functions/helloworld/

      Python

      cd python-docs-samples/functions/helloworld/

      Go

      cd golang-samples/functions/helloworld/

      Java

      cd java-docs-samples/functions/helloworld/hello-pubsub/

      Ruby

      cd ruby-docs-samples/functions/helloworld/pubsub/

    3. Echa un vistazo al código de ejemplo:

      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} message The Pub/Sub message.
       * @param {object} context The event metadata.
       */
      exports.helloPubSub = (message, context) => {
        const name = message.data
          ? Buffer.from(message.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 `@type` field maps to
                               `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                              The `data` field maps to the PubsubMessage data
                              in a base64-encoded string. The `attributes` field maps
                              to the PubsubMessage attributes if any is present.
               context (google.cloud.functions.Context): Metadata of triggering event
                              including `event_id` which maps to the PubsubMessage
                              messageId, `timestamp` which maps to the PubsubMessage
                              publishTime, `event_type` which maps to
                              `google.pubsub.topic.publish`, and `resource` which is
                              a dictionary that describes the service API endpoint
                              pubsub.googleapis.com, the triggering topic's name, and
                              the triggering event type
                              `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
          Returns:
              None. The output is written to Cloud Logging.
          """
          import base64
      
          print(
              """This Function was triggered by messageId {} published at {} to {}
          """.format(
                  context.event_id, context.timestamp, context.resource["name"]
              )
          )
      
          if "data" in event:
              name = base64.b64decode(event["data"]).decode("utf-8")
          else:
              name = "World"
          print(f"Hello {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.
      // 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 Pub/Sub message.
      func HelloPubSub(ctx context.Context, m PubSubMessage) error {
      	name := string(m.Data) // Automatically decoded from base64.
      	if name == "" {
      		name = "World"
      	}
      	log.Printf("Hello, %s!", name)
      	return nil
      }
      

      Java

      
      import com.google.cloud.functions.BackgroundFunction;
      import com.google.cloud.functions.Context;
      import functions.eventpojos.PubsubMessage;
      import java.nio.charset.StandardCharsets;
      import java.util.Base64;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      
      public class HelloPubSub implements BackgroundFunction<PubsubMessage> {
        private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());
      
        @Override
        public void accept(PubsubMessage message, Context context) {
          String name = "world";
          if (message != null && message.getData() != null) {
            name = new String(
                Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
                StandardCharsets.UTF_8);
          }
          logger.info(String.format("Hello %s!", name));
          return;
        }
      }

      Ruby

      require "functions_framework"
      require "base64"
      
      FunctionsFramework.cloud_event "hello_pubsub" do |event|
        # The event parameter is a CloudEvents::Event::V1 object.
        # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
        name = Base64.decode64 event.data["message"]["data"] rescue "World"
      
        # A cloud_event function does not return a response, but you can log messages
        # or cause side effects such as sending additional events.
        logger.info "Hello, #{name}!"
      end

    Desplegar la función

    Para desplegar la función con un activador de Pub/Sub, ejecuta el siguiente comando en el directorio que contiene el código de ejemplo (o, en el caso de Java, el archivo pom.xml):

    Node.js

    gcloud functions deploy helloPubSub \
    --runtime nodejs20 \
    --trigger-topic YOUR_TOPIC_NAME

    Usa la marca --runtime para especificar el ID del entorno de ejecución de una versión compatible de Node.js para ejecutar tu función.

    Python

    gcloud functions deploy hello_pubsub \
    --runtime python312 \
    --trigger-topic YOUR_TOPIC_NAME

    Usa la marca --runtime para especificar el ID de tiempo de ejecución de una versión de Python compatible para ejecutar tu función.

    Go

    gcloud functions deploy HelloPubSub \
    --runtime go121 \
    --trigger-topic YOUR_TOPIC_NAME

    Usa la marca --runtime para especificar el ID de tiempo de ejecución de una versión de Go compatible para ejecutar tu función.

    Java

    gcloud functions deploy java-pubsub-function \
    --entry-point functions.HelloPubSub \
    --runtime java17 \
    --memory 512MB \
    --trigger-topic YOUR_TOPIC_NAME

    Usa la marca --runtime para especificar el ID de tiempo de ejecución de una versión de Java compatible para ejecutar tu función.

    Ruby

    gcloud functions deploy hello_pubsub --runtime ruby33 \
    -
    -trigger-topic YOUR_TOPIC_NAME

    Usa la marca --runtime para especificar el ID de tiempo de ejecución de una versión de Ruby compatible para ejecutar tu función.

    donde YOUR_TOPIC_NAME es el nombre del tema de Pub/Sub al que se suscribirá la función.

    Si YOUR_TOPIC_NAME aún no existe, este comando lo creará. También puedes crear un tema antes de ejecutar el comando deploy mediante la Google Cloud consola o el siguiente comando gcloud:

    gcloud pubsub topics create YOUR_TOPIC_NAME

    Activar la función

    1. Publica un mensaje en tu tema de Pub/Sub. En este ejemplo, el mensaje es un nombre que la función incluirá en un saludo:

      gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

      Sustituye YOUR_TOPIC_NAME por el nombre de tu tema de Pub/Sub y YOUR_NAME por una cadena arbitraria.

    2. Consulta los registros para asegurarte de que las ejecuciones se han completado:

      gcloud functions logs read --limit 50

    También puedes publicar un mensaje en un tema de Pub/Sub desde una función.

    Limpieza

    Para evitar que los recursos utilizados en este tutorial se cobren en tu cuenta de Google Cloud, elimina el proyecto que contiene los recursos o conserva el proyecto y elimina los recursos.

    Eliminar el proyecto

    La forma más fácil de evitar que te cobren es eliminar el proyecto que has creado para el tutorial.

    Para ello, sigue las instrucciones que aparecen a continuación:

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    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.

    Eliminar la función

    Si eliminas funciones de Cloud Run, no se eliminarán los recursos almacenados en Cloud Storage.

    Para eliminar la función que has creado en este tutorial, ejecuta el siguiente comando:

    Node.js

    gcloud functions delete helloPubSub 

    Python

    gcloud functions delete hello_pubsub 

    Go

    gcloud functions delete HelloPubSub 

    Java

    gcloud functions delete java-pubsub-function 

    Ruby

    gcloud functions delete hello_pubsub 

    También puedes eliminar funciones de Cloud Run desde la Google Cloud consola.