Pub/Sub من Google Cloud هو ناقل رسائل موزَّع عالميًا يتوسّع تلقائيًا حسب الحاجة. يمكنك تفعيل دالة كلما تم إرسال رسالة 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، تتضمّن حزمة تطوير البرامج (SDK) لـ Firebase في 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"]