Pub/Sub 觸發條件


Google CloudPub/Sub 是遍及全球的訊息匯流排,可自動按照您的需求進行擴充。每當新的 Pub/Sub 訊息傳送至特定主題,您都可以觸發函式。

匯入必要模組

首先,請匯入處理 Pub/Sub 事件所需的模組:

Node.jsPython
const {onMessagePublished} = require("firebase-functions/v2/pubsub");
const logger = require("firebase-functions/logger");
from firebase_functions import pubsub_fn

觸發函式

您必須指定要觸發函式的 Pub/Sub 主題名稱,並在事件處理常式中設定事件:

Node.jsPython
exports.hellopubsub = onMessagePublished("topic-name", (event) => {
@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."""

存取 Pub/Sub 訊息酬載

您可以透過傳回至函式中的訊息物件,存取 Pub/Sub 訊息的酬載。如果訊息的 Pub/Sub 訊息主體含有 JSON,Cloud FunctionsFirebase SDK 就會提供輔助屬性來解碼訊息。舉例來說,以下是使用簡單 JSON 酬載發布的訊息:

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

您可以透過 json 屬性存取 JSON 資料酬載,如下所示:

Node.jsPython
  // 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);
  }
# 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"]

其他非 JSON 酬載會以 base64 編碼字串的形式,包含在 Pub/Sub 訊息的訊息物件中。如要讀取類似下方的訊息,您必須解碼 base64 編碼字串,如下所示:

gcloud pubsub topics publish topic-name --message 'MyMessage'
Node.jsPython
// Decode the PubSub Message body.
const message = event.data.message;
const messageBody = message.data ?
      Buffer.from(message.data, "base64").toString() :
      null;
# Decode the PubSub message body.
message_body = base64.b64decode(event.data.message.data)

存取訊息屬性

您可以傳送 Pub/Sub 訊息,並在發布指令中設定資料屬性。舉例來說,您可以使用 name 屬性發布訊息:

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

您可以從訊息物件的對應屬性讀取這類屬性:

Node.jsPython
// Get the `name` attribute of the message.
const name = event.data.message.attributes.name;
# 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"]