Pub/Sub от Google Cloud — это глобально распределенная шина сообщений, которая автоматически масштабируется по мере необходимости. Вы можете запускать функцию всякий раз, когда новое сообщение Pub/Sub отправляется в определенную тему.
Импортируйте необходимые модули.
Для начала импортируйте модули, необходимые для обработки событий Pub/Sub :
Node.js
const {onMessagePublished} = require("firebase-functions/pubsub");
const logger = require("firebase-functions/logger");
Python
from firebase_functions import pubsub_fn
Trigger the function
Необходимо указать имя темы Pub/Sub , для которой вы хотите запустить функцию, и задать событие внутри обработчика событий:
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."""
Access the pub/sub message payload
The payload for the Pub/Sub message is accessible from the message object returned to your function. For messages with JSON in the Pub/Sub message body, the Firebase SDK for Cloud Functions has a helper property to decode the message. For example, here is a message published with a simple JSON payload:
gcloud pubsub topics publish topic-name --message '{"name":"Xenia"}'
Доступ к данным в формате JSON можно получить следующим образом через свойство 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"]
Other, non-JSON payloads are contained in the Pub/Sub message as base64 encoded strings in the message object. To read a message like the following, you must decode the base64 encoded string as shown:
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)
Access message attributes
Сообщение Pub/Sub можно отправить с атрибутами данных, заданными в команде публикации. Например, вы можете опубликовать сообщение с атрибутом name :
gcloud pubsub topics publish topic-name --attribute name=Xenia
Такие атрибуты можно прочитать из соответствующего свойства объекта сообщения:
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"]