مشغِّلات النشر/الاشتراك

Pub/Sub من Google Cloud هو ناقل رسائل موزّع على مستوى العالم يتم توسيعه تلقائيًا حسب حاجتك. يمكنك تشغيل دالة كلما تم إرسال رسالة 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 من عنصر الرسالة الذي تم إرجاعه إلى الدالة. بالنسبة إلى الرسائل التي تتضمّن 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"]