Google Cloud ของ Pub/Sub เป็น Message Bus ที่มีการกระจายทั่วโลก ซึ่งจะปรับขนาดโดยอัตโนมัติตามความต้องการของคุณ คุณสามารถทริกเกอร์ฟังก์ชันเมื่อใดก็ตามที่มีการส่งข้อความ Pub/Sub ใหม่ ไปยังหัวข้อที่เฉพาะเจาะจง
นำเข้าโมดูลที่จำเป็น
หากต้องการเริ่มต้นใช้งาน ให้นำเข้าโมดูลที่จำเป็นสำหรับการจัดการ Pub/Sub เหตุการณ์ดังนี้
Node.js
const {onMessagePublished} = require("firebase-functions/pubsub");
const logger = require("firebase-functions/logger");
Python
from firebase_functions import pubsub_fn
ทริกเกอร์ฟังก์ชัน
คุณต้องระบุชื่อหัวข้อ Pub/Sub ที่ต้องการทริกเกอร์ฟังก์ชัน และตั้งค่าเหตุการณ์ภายในตัวจัดการเหตุการณ์ ดังนี้
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."""
เข้าถึงเพย์โหลดข้อความ Pub/Sub
คุณเข้าถึงเพย์โหลดของข้อความ Pub/Sub ได้จากออบเจ็กต์ข้อความที่ส่งกลับไปยังฟังก์ชัน สำหรับข้อความที่มี JSON ในเนื้อหาข้อความ Pub/Sub, Firebase SDK สำหรับ Cloud Functions จะมีพร็อพเพอร์ตี้ตัวช่วยในการถอดรหัสข้อความ ตัวอย่างเช่น ข้อความต่อไปนี้เผยแพร่ด้วยเพย์โหลด JSON แบบง่าย
gcloud pubsub topics publish topic-name --message '{"name":"Xenia"}'
คุณเข้าถึงเพย์โหลดข้อมูล JSON ได้ดังนี้ผ่านพร็อพเพอร์ตี้ 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"]
เพย์โหลดอื่นๆ ที่ไม่ใช่ JSON จะอยู่ในข้อความ Pub/Sub เป็น สตริงที่เข้ารหัสฐาน 64 ในออบเจ็กต์ข้อความ หากต้องการอ่านข้อความเช่นข้อความต่อไปนี้ คุณต้องถอดรหัสสตริงที่เข้ารหัสฐาน 64 ดังที่แสดง
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)
เข้าถึงแอตทริบิวต์ข้อความ
คุณสามารถส่งข้อความ Pub/Sub พร้อมแอตทริบิวต์ข้อมูลที่ตั้งค่าไว้ใน
คำสั่งเผยแพร่ ตัวอย่างเช่น คุณสามารถเผยแพร่ข้อความที่มีแอตทริบิวต์ name ได้ดังนี้
gcloud pubsub topics publish topic-name --attribute name=Xenia
คุณสามารถอ่านแอตทริบิวต์ดังกล่าวได้จากพร็อพเพอร์ตี้ที่เกี่ยวข้องของออบเจ็กต์ข้อความ ดังนี้
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"]