Tutorial su Cloud Pub/Sub (2ª generazione)


Questo semplice tutorial illustra la scrittura, il deployment e l'attivazione di una funzione Cloud Functions basata su eventi con un trigger di Cloud Pub/Sub.

Se non hai mai utilizzato Pub/Sub e vuoi saperne di più, consulta la documentazione di Pub/Sub, in particolare la gestione di argomenti e sottoscrizioni. Vedi Trigger di Google Cloud Pub/Sub per una panoramica sull'utilizzo degli argomenti e delle sottoscrizioni Pub/Sub in Cloud Functions.

Se stai cercando esempi di codice per l'utilizzo di Pub/Sub, visita il browser di esempio Google Cloud.

Obiettivi

Costi

In questo documento vengono utilizzati i seguenti componenti fatturabili di Google Cloud:

  • Cloud Functions
  • Cloud Build
  • Pub/Sub
  • Artifact Registry
  • Eventarc
  • Cloud Logging

For details, see Cloud Functions pricing.

Per generare una stima dei costi in base all'utilizzo previsto, utilizza il Calcolatore prezzi. I nuovi utenti di Google Cloud possono essere idonei a una prova senza costi aggiuntivi.

Prima di iniziare

  1. Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.
  2. Nella pagina del selettore di progetti della console Google Cloud, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  3. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  4. Abilita le API Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub.

    Abilita le API

  5. Installa Google Cloud CLI.
  6. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  7. Nella pagina del selettore di progetti della console Google Cloud, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  8. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  9. Abilita le API Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub.

    Abilita le API

  10. Installa Google Cloud CLI.
  11. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  12. Se hai già installato gcloud CLI, aggiornalo eseguendo questo comando:

    gcloud components update
  13. Preparare l'ambiente di sviluppo.

Prerequisiti

Crea un argomento Pub/Sub:

gcloud pubsub topics create YOUR_TOPIC_NAME

Questo è un passaggio obbligatorio prima di poter eseguire il deployment della funzione. In Cloud Functions (2nd gen), gli argomenti Pub/Sub non vengono creati automaticamente quando esegui il deployment di una funzione.

Preparazione dell'applicazione

  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 l'esempio come file ZIP ed estrarlo.

    Python

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

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    Go

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

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    Java

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

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    C#

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

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    Ruby

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

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    PHP

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

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

  2. Passa alla directory che contiene il codice campione di Cloud Functions per accedere a Pub/Sub:

    Node.js

    cd nodejs-docs-samples/functions/v2/helloPubSub/

    Python

    cd python-docs-samples/functions/v2/pubsub/

    Go

    cd golang-samples/functions/functionsv2/hellopubsub/

    Java

    cd java-docs-samples/functions/v2/pubsub/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloPubSub/

    Ruby

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

    PHP

    cd php-docs-samples/functions/helloworld_pubsub/

  3. Dai un'occhiata al codice campione:

    Node.js

    const functions = require('@google-cloud/functions-framework');
    
    // Register a CloudEvent callback with the Functions Framework that will
    // be executed when the Pub/Sub trigger topic receives a message.
    functions.cloudEvent('helloPubSub', cloudEvent => {
      // The Pub/Sub message is passed as the CloudEvent's data payload.
      const base64name = cloudEvent.data.message.data;
    
      const name = base64name
        ? Buffer.from(base64name, 'base64').toString()
        : 'World';
    
      console.log(`Hello, ${name}!`);
    });

    Python

    import base64
    
    from cloudevents.http import CloudEvent
    import functions_framework
    
    
    # Triggered from a message on a Cloud Pub/Sub topic.
    @functions_framework.cloud_event
    def subscribe(cloud_event: CloudEvent) -> None:
        # Print out the data from Pub/Sub, to prove that it worked
        print(
            "Hello, " + base64.b64decode(cloud_event.data["message"]["data"]).decode() + "!"
        )
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"context"
    	"fmt"
    	"log"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    	"github.com/cloudevents/sdk-go/v2/event"
    )
    
    func init() {
    	functions.CloudEvent("HelloPubSub", helloPubSub)
    }
    
    // MessagePublishedData contains the full Pub/Sub message
    // See the documentation for more details:
    // https://cloud.google.com/eventarc/docs/cloudevents#pubsub
    type MessagePublishedData struct {
    	Message PubSubMessage
    }
    
    // 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 CloudEvent message and extracts the Pub/Sub message.
    func helloPubSub(ctx context.Context, e event.Event) error {
    	var msg MessagePublishedData
    	if err := e.DataAs(&msg); err != nil {
    		return fmt.Errorf("event.DataAs: %w", err)
    	}
    
    	name := string(msg.Message.Data) // Automatically decoded from base64.
    	if name == "" {
    		name = "World"
    	}
    	log.Printf("Hello, %s!", name)
    	return nil
    }
    

    Java

    import com.google.cloud.functions.CloudEventsFunction;
    import com.google.gson.Gson;
    import functions.eventpojos.PubSubBody;
    import io.cloudevents.CloudEvent;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import java.util.logging.Logger;
    
    public class SubscribeToTopic implements CloudEventsFunction {
      private static final Logger logger = Logger.getLogger(SubscribeToTopic.class.getName());
    
      @Override
      public void accept(CloudEvent event) {
        // The Pub/Sub message is passed as the CloudEvent's data payload.
        if (event.getData() != null) {
          // Extract Cloud Event data and convert to PubSubBody
          String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
          Gson gson = new Gson();
          PubSubBody body = gson.fromJson(cloudEventData, PubSubBody.class);
          // Retrieve and decode PubSub message data
          String encodedData = body.getMessage().getData();
          String decodedData =
              new String(Base64.getDecoder().decode(encodedData), StandardCharsets.UTF_8);
          logger.info("Hello, " + decodedData + "!");
        }
      }
    }

    C#

    using CloudNative.CloudEvents;
    using Google.Cloud.Functions.Framework;
    using Google.Events.Protobuf.Cloud.PubSub.V1;
    using Microsoft.Extensions.Logging;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace HelloPubSub;
    
    public class Function : ICloudEventFunction<MessagePublishedData>
    {
        private readonly ILogger _logger;
    
        public Function(ILogger<Function> logger) =>
            _logger = logger;
    
        public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
        {
            string nameFromMessage = data.Message?.TextData;
            string name = string.IsNullOrEmpty(nameFromMessage) ? "world" : nameFromMessage;
            _logger.LogInformation("Hello {name}", name);
            return Task.CompletedTask;
        }
    }

    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

    PHP

    
    use CloudEvents\V1\CloudEventInterface;
    use Google\CloudFunctions\FunctionsFramework;
    
    // Register the function with Functions Framework.
    // This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment
    // variable when deploying. The `FUNCTION_TARGET` environment variable should
    // match the first parameter.
    FunctionsFramework::cloudEvent('helloworldPubsub', 'helloworldPubsub');
    
    function helloworldPubsub(CloudEventInterface $event): void
    {
        $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
    
        $cloudEventData = $event->getData();
        $pubSubData = base64_decode($cloudEventData['message']['data']);
    
        $name = $pubSubData ? htmlspecialchars($pubSubData) : 'World';
        fwrite($log, "Hello, $name!" . PHP_EOL);
    }

Deployment della funzione

Per eseguire 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):

// LINT.IfChange(nodejs_version) // LINT.QuindiChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.thenChange(:nodejs_version)

Node.js

gcloud functions deploy nodejs-pubsub-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloPubSub \
--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 python-pubsub-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=subscribe \
--trigger-topic=YOUR_TOPIC_NAME

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

Go

gcloud functions deploy go-pubsub-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloPubSub \
--trigger-topic=YOUR_TOPIC_NAME

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

Java

gcloud functions deploy java-pubsub-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.SubscribeToTopic \
--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.

C#

gcloud functions deploy csharp-pubsub-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloPubSub.Function \
--trigger-topic=YOUR_TOPIC_NAME

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

Ruby

gcloud functions deploy ruby-pubsub-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_pubsub \
--trigger-topic=YOUR_TOPIC_NAME

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

PHP

gcloud functions deploy php-pubsub-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloworldPubsub \
--trigger-topic=YOUR_TOPIC_NAME

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

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

Prima di eseguire il comando deploy, devi creare un argomento utilizzando la console Google Cloud o lo strumento a riga di comando gcloud. A differenza di Cloud Functions (1ª generazione), in Cloud Functions (2nd gen), gli argomenti Pub/Sub non vengono creati automaticamente quando esegui il deployment di una funzione con un trigger Pub/Sub.

Attivazione della funzione

Per testare la funzione Pub/Sub:

  1. Pubblica un messaggio nell'argomento:

    gcloud pubsub topics publish my-topic --message="Friend"
    
  2. Leggi i log delle funzioni per vedere il risultato:

    gcloud functions logs read \
      --gen2 \
      --region=REGION \
      --limit=5 \
      FUNCTION_NAME
    

    Sostituisci quanto segue:

    • REGION è il nome della regione Google Cloud in cui hai eseguito il deployment della funzione (ad esempio us-west1).
    • FUNCTION_NAME è il nome che hai assegnato alla funzione quando ne hai eseguito il deployment (ad esempio, la funzione Node.js in questo tutorial è stata eseguita con il nome della funzione nodejs-pubsub-function).

    Dovresti vedere l'output di logging che include il nuovo messaggio "Amico".

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.

Elimina il progetto

Il modo più semplice per eliminare la fatturazione è eliminare il progetto che hai creato per il tutorial.

Per eliminare il progetto:

  1. Nella console Google Cloud, vai alla pagina Gestisci risorse.

    Vai a Gestisci risorse

  2. Nell'elenco dei progetti, seleziona il progetto che vuoi eliminare, quindi fai clic su Elimina.
  3. Nella finestra di dialogo, digita l'ID del progetto e fai clic su Chiudi per eliminare il progetto.

Eliminazione della Cloud Function

L'eliminazione di Cloud Functions non rimuove le risorse archiviate in Cloud Storage.

Per eliminare la Cloud Function creata in questo tutorial, esegui questo comando:

Node.js

gcloud functions delete nodejs-pubsub-function --gen2 --region REGION 

Python

gcloud functions delete python-pubsub-function --gen2 --region REGION 

Go

gcloud functions delete go-pubsub-function --gen2 --region REGION 

Java

gcloud functions delete java-pubsub-function --gen2 --region REGION 

C#

gcloud functions delete csharp-pubsub-function --gen2 --region REGION 

Ruby

gcloud functions delete ruby-pubsub-function --gen2 --region REGION 

PHP

gcloud functions delete php-pubsub-function --gen2 --region REGION 

Puoi anche eliminare Cloud Functions dalla console Google Cloud.