Pub/Sub من Google Cloud هو حافلة رسائل موزّعة على مستوى العالم يتم توسيع نطاقها تلقائيًا حسب الحاجة. يمكنك بدء وظيفة عند إرسال رسالة 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 من ملفåetmessage object returned إلى وظيفتك. بالنسبة إلى الرسائل التي تحتوي على تنسيق JSON في Pub/Sub الرسالة، تحتوي حزمة SDK الخاصة بتطبيق Firebase على 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 في رسالة Pub/Sub على شكل سلاسل مُشفَّرة بترميز base64 في عنصر الرسالة. لقراءة رسالة مثل الرسالة التالية، يجب فك ترميز السلسلة المشفّرة بترميز 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"]