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

Google Cloud's Pub/Sub là một bus thông báo được phân phối trên toàn cầu, tự động điều chỉnh quy mô theo nhu cầu của bạ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 Pub/Sub sự kiện:

Node.js

const {onMessagePublished} = require("firebase-functions/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 dữ liệu thông báo pub/sub

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

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

Bạn có thể truy cập vào 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 dữ liệu khác không phải JSON có trong thông báo Pub/Sub dưới dạng 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 thông báo

Pub/Sub thông báo có thể được gửi kèm theo các thuộc tính dữ liệu được đặt trong lệnh xuất bản. 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"]