Điều kiện kích hoạt Pub/Sub

Pub/Sub của Google Cloud là một bus thông báo được phân phối trên toàn cầu và tự động mở rộng quy mô khi bạn cần. Bạn có thể kích hoạt một hàm bất cứ khi nào một thông báo Pub/Sub mới được gửi đến một chủ đề cụ thể.

Nhập các mô-đun bắt buộc

Để bắt đầu, hãy nhập các mô-đun cần thiết để xử lý các sự kiện Pub/Sub:

Node.js

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

Python

from firebase_functions import pubsub_fn

Kích hoạt hàm

Bạn phải chỉ định tên chủ đề Pub/Sub mà bạn muốn kích hoạt hàm và đặt sự kiện trong trình xử lý sự kiện:

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

Truy cập vào tải trọng thông báo pub/sub

Bạn có thể truy cập vào tải trọng của thông báo Pub/Sub từ đối tượng thông báo được trả về cho hàm của bạn. Đối với các thông báo có JSON trong nội dung thông báo Pub/Sub, SDK Firebase cho Cloud Functions có một thuộc tính trợ giúp để giải mã thông báo. Ví dụ: sau đây là một thông báo được xuất bản bằng một tải trọng JSON đơn giản:

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

Bạn có thể truy cập vào một tải trọng dữ liệu JSON như thế này thông qua thuộc tính 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"]

Các tải trọng không phải JSON khác có trong thông báo Pub/Sub dưới dạng các chuỗi được mã hoá base64 trong đối tượng thông báo. Để đọc một thông báo như sau, bạn phải giải mã chuỗi được mã hoá base64 như minh hoạ:

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)

Truy cập vào các thuộc tính của thư

Thông báo Pub/Sub có thể được gửi cùng với các thuộc tính dữ liệu được đặt trong lệnh publish. Ví dụ: bạn có thể xuất bản một thông báo có thuộc tính name:

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

Bạn có thể đọc các thuộc tính như vậy từ thuộc tính tương ứng của đối tượng thông báo:

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