Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Google Cloud's Pub/Sub è un
bus di messaggi distribuito a livello globale che scala automaticamente in base alle esigenze.
Puoi attivare una funzione ogni volta che un nuovo messaggio Pub/Sub viene inviato
a un argomento specifico.
Importa i moduli richiesti
Per iniziare, importa i moduli necessari per la gestione degli eventi Pub/Sub:
@pubsub_fn.on_message_published(topic="topic-name")defhellopubsub(event:pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData])-> None:"""Log a message using data published to a Pub/Sub topic."""
Il payload per il messaggio Pub/Sub è accessibile dall'oggetto messaggio restituito alla tua funzione. Per i messaggi con JSON nel corpo del messaggio Pub/Sub, l'SDK Firebase per Cloud Functions ha una proprietà helper per decodificare il messaggio. Ad esempio, ecco un messaggio pubblicato con un semplice payload JSON:
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.letname=null;try{name=event.data.message.json.name;}catch(e){logger.error("PubSub message was not JSON",e);}
# Get the `name` attribute of the PubSub message JSON body.try:data=event.data.message.jsonexceptValueError:print("PubSub message was not JSON")returnifdataisNone:returnif"name"notindata:print("No 'name' key")returnname=data["name"]
Altri payload non JSON sono contenuti nel messaggio Pub/Sub come
stringhe con codifica base64 nell'oggetto messaggio. Per leggere un messaggio come il
seguente, devi decodificare la stringa con codifica base64 come mostrato:
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:
# Get the `name` attribute of the message.if"name"notinevent.data.message.attributes:print("No 'name' attribute")returnname=event.data.message.attributes["name"]
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-06 UTC."],[],[],null,["\u003cbr /\u003e\n\nGoogle Cloud's [Pub/Sub](https://cloud.google.com/pubsub/docs/) is a\nglobally distributed message bus that automatically scales as you need it.\nYou can trigger a function whenever a new Pub/Sub message is sent\nto a specific topic.\n\nImport the required modules\n\nTo get started, import the modules required for handling Pub/Sub\nevents: \n\nNode.js \n\n const {onMessagePublished} = require(\"firebase-functions/v2/pubsub\");\n const logger = require(\"firebase-functions/logger\"); \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L19-L20\n\nPython \n\n from firebase_functions import pubsub_fn \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L18-L18\n\nTrigger the function\n\nYou must specify the Pub/Sub topic name that\nyou want to trigger your function, and set the event within the\nevent handler: \n\nNode.js \n\n exports.hellopubsub = onMessagePublished(\"topic-name\", (event) =\u003e { \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L29-L29\n\nPython \n\n @pubsub_fn.on_message_published(topic=\"topic-name\")\n def hellopubsub(event: pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData]) -\u003e None:\n \"\"\"Log a message using data published to a Pub/Sub topic.\"\"\" \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L24-L26\n\nAccess the pub/sub message payload\n\nThe payload for the Pub/Sub message is accessible from the\nmessage object returned\nto your function. For messages with JSON in the Pub/Sub message\nbody, the Firebase SDK for Cloud Functions has a helper property to decode the message. For\nexample, here is a message published with a simple JSON payload: \n\n gcloud pubsub topics publish topic-name --message '{\"name\":\"Xenia\"}'\n\nYou can access a JSON data payload like this via the\n`json` property: \n\nNode.js \n\n```javascript\n // Get the `name` attribute of the PubSub message JSON body.\n let name = null;\n try {\n name = event.data.message.json.name;\n } catch (e) {\n logger.error(\"PubSub message was not JSON\", e);\n }https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L51-L57\n```\n\nPython \n\n # Get the `name` attribute of the PubSub message JSON body.\n try:\n data = event.data.message.json\n except ValueError:\n print(\"PubSub message was not JSON\")\n return\n if data is None:\n return\n if \"name\" not in data:\n print(\"No 'name' key\")\n return\n name = data[\"name\"] \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L42-L53\n\nOther, non-JSON payloads are contained in the Pub/Sub message as\nbase64 encoded strings in the message object. To read a message like the\nfollowing, you must decode the base64 encoded string as shown: \n\n gcloud pubsub topics publish topic-name --message 'MyMessage'\n\nNode.js \n\n```javascript\n// Decode the PubSub Message body.\nconst message = event.data.message;\nconst messageBody = message.data ?\n Buffer.from(message.data, \"base64\").toString() :\n null;https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L32-L36\n```\n\nPython \n\n # Decode the PubSub message body.\n message_body = base64.b64decode(event.data.message.data) \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L29-L30\n\nAccess message attributes\n\nPub/Sub message can be sent with data attributes set in the\npublish command. For example, you could publish a message with a `name`\nattribute: \n\n gcloud pubsub topics publish topic-name --attribute name=Xenia\n\nYou can read such attributes from the corresponding property of the\nmessage object: \n\nNode.js \n\n```javascript\n// Get the `name` attribute of the message.\nconst name = event.data.message.attributes.name;https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L71-L72\n```\n\nPython \n\n # Get the `name` attribute of the message.\n if \"name\" not in event.data.message.attributes:\n print(\"No 'name' attribute\")\n return\n name = event.data.message.attributes[\"name\"] \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L64-L68"]]