Pub/Sub ของ Google Cloud คือ Message Bus ที่กระจายอยู่ทั่วโลกซึ่งจะปรับขนาดโดยอัตโนมัติตามที่คุณต้องการ คุณสามารถทริกเกอร์ฟังก์ชันเมื่อใดก็ตามที่มีการส่งข้อความ Pub/Sub ใหม่ ไปยังหัวข้อที่เฉพาะเจาะจง
นำเข้าโมดูลที่จำเป็น
หากต้องการเริ่มต้นใช้งาน ให้นำเข้าโมดูลที่จำเป็นสำหรับการจัดการPub/Sub เหตุการณ์
Node.js
const {onMessagePublished} = require("firebase-functions/v2/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ข้อความในรูปแบบ สตริงที่เข้ารหัส Base64 ในออบเจ็กต์ข้อความ หากต้องการอ่านข้อความเช่น ข้อความต่อไปนี้ คุณต้องถอดรหัสสตริงที่เข้ารหัส Base64 ดังที่แสดง
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"]