Tutorial su Cloud Pub/Sub (1ª generazione.)


Questo semplice tutorial mostra come scrivere, eseguire il deployment e attivare una funzione Cloud Run basata su eventi con un trigger Pub/Sub.

Se non hai mai utilizzato Pub/Sub e vuoi saperne di più, consulta la documentazione di Pub/Sub, in particolare la sezione relativa alla gestione di argomenti e sottoscrizioni. Consulta la sezione Trigger Pub/Sub per una panoramica dell'utilizzo di argomenti e sottoscrizioni Pub/Sub nelle funzioni Cloud Run.

Se stai cercando esempi di codice per utilizzare Pub/Sub, visita il browser degli esempi.

Obiettivi

Costi

In questo documento, utilizzi i seguenti componenti fatturabili di Google Cloud:

  • Cloud Run functions
  • Pub/Sub

Per generare una stima dei costi in base all'utilizzo previsto, utilizza il calcolatore prezzi.

I nuovi Google Cloud utenti potrebbero avere diritto a una prova gratuita.

Prima di iniziare

  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.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

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

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

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

    Go to project selector

  9. Make sure that billing is enabled for your Google Cloud project.

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

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. Se hai già installato gcloud CLI, aggiornala eseguendo il seguente comando:

    gcloud components update
  15. Prepara l'ambiente di sviluppo.

Preparazione della richiesta

  1. Clona il repository dell'app di esempio sulla tua macchina locale:

    Node.js

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

    In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

    Python

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

    In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

    Vai

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

    In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

    Java

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

    In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

    Ruby

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

    In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

  2. Passa alla directory che contiene il codice campione di Cloud Run Functions per l'accesso a Pub/Sub:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Vai

    cd golang-samples/functions/helloworld/

    Java

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

    Ruby

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

  3. Dai un'occhiata al codice campione:

    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

Deployment della funzione

Per il deployment della funzione con un trigger Pub/Sub, esegui questo comando nella directory che contiene il codice campione (o, nel caso di Java, il file pom.xml):

Node.js

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

Utilizza il flag --runtime per specificare l'ID runtime di una versione di Node.js supportata per eseguire la funzione.

Python

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

Utilizza il flag --runtime per specificare l'ID runtime di una versione di Python supportata per eseguire la funzione.

Vai

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

Utilizza il flag --runtime per specificare l'ID runtime di una versione di Go supportata per eseguire la funzione.

Java

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

Utilizza il flag --runtime per specificare l'ID runtime di una versione Java supportata per eseguire la funzione.

Ruby

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

Utilizza il flag --runtime per specificare l'ID runtime di una versione di Ruby supportata per eseguire la funzione.

dove YOUR_TOPIC_NAME è il nome dell'argomento Pub/Sub a cui verrà sottoscritta la funzione.

Se YOUR_TOPIC_NAME non esiste già, questo comando lo crea per te. Puoi anche creare un argomento prima di eseguire il comando deploy utilizzando la Google Cloud console o il seguente comando gcloud:

gcloud pubsub topics create YOUR_TOPIC_NAME

Attivazione della funzione

  1. Pubblica un messaggio nell'argomento Pub/Sub. In questo esempio, il messaggio è un nome che la funzione includerà in un saluto:

    gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

    Sostituisci YOUR_TOPIC_NAME con il nome dell'argomento Pub/Sub e YOUR_NAME con una stringa arbitraria.

  2. Controlla i log per assicurarti che le esecuzioni siano state completate:

    gcloud functions logs read --limit 50

Puoi anche pubblicare un messaggio in un argomento Pub/Sub dall'interno di una funzione.

Esegui la pulizia

Per evitare che al tuo Account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questo tutorial, elimina il progetto che contiene le risorse oppure mantieni il progetto ed elimina le singole risorse.

Eliminazione del progetto

Il modo più semplice per eliminare la fatturazione è quello di eliminare il progetto creato per il tutorial.

Per eliminare il progetto:

  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.

Eliminazione della funzione

L'eliminazione delle funzioni Cloud Run non rimuove le risorse archiviate in Cloud Storage.

Per eliminare la funzione creata in questo tutorial, esegui questo comando:

Node.js

gcloud functions delete helloPubSub 

Python

gcloud functions delete hello_pubsub 

Vai

gcloud functions delete HelloPubSub 

Java

gcloud functions delete java-pubsub-function 

Ruby

gcloud functions delete hello_pubsub 

Puoi anche eliminare le funzioni Cloud Run dalla consoleGoogle Cloud .