Aktywatory Pub/Sub

Google CloudPub/Sub to globalna magistrala komunikatów, która automatycznie skaluje się w zależności od potrzeb. Funkcję możesz wywołać za każdym razem, gdy nowa wiadomość Pub/Sub zostanie wysłana na określony temat.

Zaimportuj wymagane moduły.

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

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ć Pub/Subnazwę tematu, który ma uruchamiać funkcję, i ustawić zdarzenie w ramach procedury obsługi zdarzeń:

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 wiadomości Pub/Sub

Ładunek wiadomości Pub/Sub jest dostępny w obiekcie wiadomości zwróconym do funkcji. W przypadku wiadomości z JSON-em w Pub/Subtreści wiadomościFirebase pakiet SDK Firebase na Cloud Functions ma właściwość pomocniczą do dekodowania wiadomości. Na przykład oto wiadomość opublikowana z prostym ładunkiem JSON:

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

Do ładunku danych JSON możesz uzyskać dostęp w ten sposób 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, które nie są w formacie JSON, są zawarte w wiadomości Pub/Sub jako ciągi tekstowe zakodowane w formacie Base64 w obiekcie wiadomości. Aby odczytać wiadomość podobną do tej poniżej, musisz zdekodować ciąg tekstowy zakodowany w formacie base64, jak pokazano poniżej:

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 można wysłać z atrybutami danych ustawionymi w poleceniu publikowania. 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"]