Google Cloud 的Pub/Sub是一種全球分佈式消息總線,可根據您的需要自動擴展。您可以使用functions.pubsub
創建處理 Pub/Sub 事件的函數。
觸發發布/訂閱功能
每當將新的 Pub/Sub 消息發送到特定主題時,您都可以觸發一個函數。您必須指定要觸發函數的 Pub/Sub 主題名稱,並在onPublish()
事件處理程序中設置事件:
exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish((message) => { // ... });
訪問發布/訂閱消息負載
Pub/Sub 消息的有效負載可從返回給您的函數Message
對象訪問。對於 Pub/Sub 消息正文中包含 JSON 的消息,適用於 Cloud Functions 的 Firebase SDK 具有用於解碼消息的輔助屬性。例如,這是一條使用簡單的 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 = message.json.name; } catch (e) { functions.logger.error('PubSub message was not JSON', e); }
其他非 JSON 有效負載作為消息對像中的 base64 編碼字符串包含在 Pub/Sub 消息中。要閱讀如下所示的消息,您必須解碼 base64 編碼的字符串,如下所示:
gcloud pubsub topics publish topic-name --message 'MyMessage'
// Decode the PubSub Message body. const messageBody = message.data ? Buffer.from(message.data, 'base64').toString() : null;
訪問消息屬性
可以使用發布命令中設置的數據屬性發送發布/訂閱消息。例如,您可以發布一條帶有name
屬性的消息:
gcloud pubsub topics publish topic-name --attribute name=Xenia
您可以從Message.attributes
中讀取此類屬性:
// Get the `name` attribute of the message. const name = message.attributes.name;
您可能會注意到消息 ID 或消息發佈時間等一些基本數據在Message.attributes
中不可用。要解決此問題,您可以在觸發事件的EventContext
中訪問這些詳細信息。例如:
exports.myFunction = functions.pubsub.topic('topic1').onPublish((message, context) => {
console.log('The function was triggered at ', context.timestamp);
console.log('The unique ID for the event is', context.eventId);
});