【问题标题】:Google Cloud PubSub - How to send multiple arguments to the Cloud FunctionGoogle Cloud PubSub - 如何向 Cloud Function 发送多个参数
【发布时间】:2020-05-07 14:52:35
【问题描述】:

我一直在使用 Google Cloud PubSub 来触发 Google Cloud Functions。到目前为止,我一直在使用单个参数“uuid”,现在我还需要发送开发/生产标志。

以下是 Google App Engine/Django 中的发布者:

    publisher = pubsub_v1.PublisherClient()
    topic_name = 'projects/project/topics/cloudfunction_topic'
    message_to_publish = video.uuid
    publisher.publish(topic_name, data=message_to_publish.encode('utf-8'), spam='')

下面是 GCF 中的订阅者部分:

    if os.getenv('GCF', None):
        uuid = base64.b64decode(event['data']).decode('utf-8')

我应该如何更改此设置,以便消息中可以有多个参数(video.uuid、生产/开发)?

【问题讨论】:

  • 尝试将数据字典序列化为 JSON。这可以是您消息的有效负载。

标签: python django google-cloud-platform google-cloud-functions google-cloud-pubsub


【解决方案1】:

最简单的方法(IMO)是创建一个json结构,并在发送端将其序列化为utf-8字符串,然后在GCF中将其反序列化回json结构。

【讨论】:

  • 您也可以将参数作为属性放入 PubSub 消息中。一切都取决于它们的用途。
【解决方案2】:

Pub/Sub 消息是 base64 编码的,因此您可以编写 json 并将其从 Pub/Sub 发送到 Cloud Function,或者您可以从 Pub/Bub 传递 Attributes,即 json 和纯文本。

例如,如果您像这样手动运行 Pub/Sub:

你可以添加属性:

“test”这个词是base64,但console.dir(event)是这样的……

    exports.getData = (event, context) => {...
      console.dir(event);

...将在 Cloud Logging 中显示:

然后在您的 Cloud Function 中解析和使用 Pub/Sub 属性就相当容易了。显然,这是 Node,但在 Python 中会类似。

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多