Pub/Sub di Google Cloud è un bus di messaggi distribuito a livello globale che scala automaticamente in base alle esigenze. Puoi attivare una funzione ogni volta che viene inviato un nuovo messaggio Pub/Sub a un argomento specifico.
Importa i moduli richiesti
Per iniziare, importa i moduli necessari per gestire gli eventi Pub/Sub:
Node.js
const {onMessagePublished} = require("firebase-functions/v2/pubsub");
const logger = require("firebase-functions/logger");
Python
from firebase_functions import pubsub_fn
Attiva la funzione
Devi specificare il nome dell'argomento Pub/Sub per attivare la funzione e impostare l'evento all'interno del gestore eventi:
Node.js
exports.hellopubsub = onMessagePublished("topic-name", (event) => {
Python
@pubsub_fn.on_message_published(topic="topic-name")
def hellopubsub(event: pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData]) -> None:
"""Log a message using data published to a Pub/Sub topic."""
Accedere al payload del messaggio Pub/Sub
Il payload per il messaggio Pub/Sub è accessibile dall'oggetto messaggio restituito alla funzione. Per i messaggi con JSON nel corpo del messaggio Pub/Sub, l'SDK Firebase per Cloud Functions ha una proprietà di supporto per decodificare il messaggio. Ad esempio, ecco un messaggio pubblicato con un semplice payload JSON:
gcloud pubsub topics publish topic-name --message '{"name":"Xenia"}'
Puoi accedere a un payload di dati JSON come questo tramite la proprietà
json
:
Node.js
// Get the `name` attribute of the PubSub message JSON body. let name = null; try { name = event.data.message.json.name; } catch (e) { logger.error("PubSub message was not JSON", e); }
Python
# Get the `name` attribute of the PubSub message JSON body.
try:
data = event.data.message.json
except ValueError:
print("PubSub message was not JSON")
return
if data is None:
return
if "name" not in data:
print("No 'name' key")
return
name = data["name"]
Altri payload non JSON sono contenuti nel messaggio Pub/Sub come stringhe codificate in base64 nell'oggetto messaggio. Per leggere un messaggio come quello riportato di seguito, devi decodificare la stringa con codifica base64 come mostrato:
gcloud pubsub topics publish topic-name --message 'MyMessage'
Node.js
// Decode the PubSub Message body. const message = event.data.message; const messageBody = message.data ? Buffer.from(message.data, "base64").toString() : null;
Python
# Decode the PubSub message body.
message_body = base64.b64decode(event.data.message.data)
Accedere agli attributi dei messaggi
Il messaggio Pub/Sub può essere inviato con gli attributi dei dati impostati nel
comando publish. Ad esempio, puoi pubblicare un messaggio con un attributo name
:
gcloud pubsub topics publish topic-name --attribute name=Xenia
Puoi leggere questi attributi dalla proprietà corrispondente dell'oggetto messaggio:
Node.js
// Get the `name` attribute of the message. const name = event.data.message.attributes.name;
Python
# Get the `name` attribute of the message.
if "name" not in event.data.message.attributes:
print("No 'name' attribute")
return
name = event.data.message.attributes["name"]