GCP Pub/SubのメッセージはCloud Functionsへどう届くか
概要
GCP Pub/SubをTriggerにしたCloud Functionは、メッセージをどう受け取るのか調べてみました。
実験
試しに次のようにメッセージをPublishしてみます。
すると、次のようになりました。
attributes
にメッセージ属性が入り、data
にメッセージ本文が入ってくるようです。
exports.test = (pubSubEvent, context) => {
console.log(pubSubEvent)
};
// -> {"@type":"type.googleapis.com/google.pubsub.v1.PubsubMessage","attributes":{"key":"value"},"data":"bWVzc2FnZQ=="}
しかしメッセージ本文はbase64で格納されているため、使える形にするにはデコードする必要があります。
The payload of the PubsubMessage object, the data published to the topic, is stored as a base64-encoded string in the data attribute of the PubsubMessage. To extract the payload of the PubsubMessage object, you may need to decode the data attribute as shown in the examples below.
ref) https://cloud.google.com/functions/docs/calling/pubsub#event_structure
exports.test = (pubSubEvent, context, callback) => {
console.log(Buffer.from(pubSubEvent.data, 'base64').toString())
};
// -> message
Cloud Schedulerの場合
Cloud SchedulerでPub/SubをPublishするとき、payloadを指定できます。
このpayloadは、data
の中に入ってくるようです。
attributesを指定するには、gcloudコマンド経由でジョブを作成すると良いようです。
ref) Cloud Schedulerのジョブにattributesを設定する
Context
ちなみにcontextの中身は、こちらに記載されていました。
TypeScriptで書くとこんな感じ
type Context = {
eventId: string,
timestamp: string,
eventType: string,
resource: string
}
Author And Source
この問題について(GCP Pub/SubのメッセージはCloud Functionsへどう届くか), 我々は、より多くの情報をここで見つけました https://qiita.com/dorarep/items/359af189f24fee8e3b3c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .