Aktywatory Pub/Sub


Pub/Sub Google Cloud to globalnie rozproszona magistrala komunikatów, która automatycznie dostosowuje się do potrzeb. Funkcję możesz wywołać za każdym razem, gdy na określony temat zostanie wysłana nowa wiadomość Pub/Sub.

Zaimportuj wymagane moduły

Aby rozpocząć, zaimportuj moduły wymagane do obsługi zdarzeń Pub/Sub:

Node.js

const {onMessagePublished} = require("firebase-functions/v2/pubsub");
const logger = require("firebase-functions/logger");

Python

from firebase_functions import pubsub_fn

Wywoływanie funkcji

Musisz podać nazwę tematu Pub/Sub, który ma wywoływać funkcję, i ustawić zdarzenie w obiekcie obsługującym zdarzenie:

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."""

Dostęp do ładunku komunikatu pub/sub

Dane ładunku wiadomości Pub/Sub są dostępne w obiekcie message zwróconym do Twojej funkcji. W przypadku wiadomości z danymi JSON w ciele wiadomości Pub/Sub pakiet SDK Firebase dla Cloud Functions ma pomocniczą właściwość służącą do dekodowania wiadomości. Oto przykład wiadomości opublikowanej z prostym ładunkiem JSON:

gcloud pubsub topics publish topic-name --message '{"name":"Xenia"}'

Do ładunku danych JSON możesz uzyskać dostęp za pomocą właściwości 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"]

Inne ładunki inne niż JSON są zawarte w wiadomości Pub/Sub jako ciągi znaków zakodowane w standardzie Base64 w obiekcie wiadomości. Aby odczytać wiadomość w takim formacie, musisz odkodować ciąg tekstowy zakodowany w formacie base64 w ten sposób:

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)

Dostęp do atrybutów wiadomości

Pub/Sub wiadomość może być wysyłana z atrybutami danych ustawionymi w poleceniu publish. Możesz na przykład opublikować wiadomość z atrybutem name:

gcloud pubsub topics publish topic-name --attribute name=Xenia

Możesz odczytać te atrybuty z odpowiedniej właściwości obiektu wiadomości:

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"]