Pub/Sub 触发器


Google CloudPub/Sub 是一个覆盖全球的分布式消息总线,可根据需要自动扩缩。您可以在有新的 Pub/Sub 消息发送到特定主题时触发函数。

首先,导入处理 Pub/Sub 事件所需的模块:

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

触发函数

您必须指定要用于触发函数的 Pub/Sub 主题名称,并在事件处理程序中设置事件:

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 消息,Firebase SDK for Cloud Functions 有一个辅助属性用于解码消息。例如,以下是一条已发布的具有简单 JSON 载荷的消息:

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

您可以通过 json 属性访问这类 JSON 数据载荷,例如:

  // 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'
// 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 消息可以具有在 publish 命令中设置的数据属性。例如,您可以发布具有 name 属性的消息:

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

您可以从消息对象的相应属性中读取此类属性:

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