【问题标题】:Consume PubSub in Google cloud function在谷歌云功能中使用 PubSub
【发布时间】:2020-07-22 00:48:05
【问题描述】:

基于官方document

我尝试使用“PubSub Pull Subscription”触发器创建云功能

import base64

def hello_pubsub(event, context):
    """Triggered from a message on a Cloud Pub/Sub topic.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    print("This Function was triggered by messageId {} published at {}".format(context.event_id, context.timestamp))

    if 'data' in event:
        name = base64.b64decode(event['data']).decode('utf-8')
    print('"{}" received!'.format(name))
    
    if 'attributes' in event:
        print(event['attributes'])

    if '@type' in event:
        print(event['@type'])  

然后我找到一个article 说“云函数在调用时会发送ACK”,和官方文档一致。

但是,当云函数处理完 PubSub 消息后,“未确认消息数”不会减少(如上图所示)

因此,我在本地尝试google-cloud-pubsub

subscription_path = subscriber.subscription_path(PROJECT, SUBSCRIPTION)
response = subscriber.pull(subscription_path, max_messages=5)

for msg in response.received_messages:
    print("Received message:", msg.message.data)

ack_ids = [msg.ack_id for msg in response.received_messages]
subscriber.acknowledge(subscription_path, ack_ids)

这样,消息计数成功减少。

我的问题是:

  • 我的云函数脚本中是否缺少某些内容?
  • 如何在我的云函数中真正“使用”PubSub 消息?

欢迎提出建议,谢谢。

【问题讨论】:

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


    【解决方案1】:

    有了 PubSub,您就有了发布者,可以将消息发布到主题中。消息在每个现有订阅中重复(在主题上创建)。最后,订阅者可以收听订阅。

    所以,在这里,您有 1 个主题和 1 个请求订阅。您还有一个部署在 topic 上的 Cloud Functions(在 gcloud cli 中,param --trigger-topic=myTopic)。 主题,而不是订阅。

    返回订阅页面,您应该会看到 2 个订阅:您的拉取订阅,以及对一个奇怪端点的推送订阅

    因此,您的消息在 2 个订阅中发布。如果您查看您的 Pull 订阅,除了您在本地的代码之外,没有任何内容会消耗其中的消息。云函数中的日志应显示正确的消息处理。

    是不是更清楚了?

    编辑

    准确来说你的情况:

    • 您的 Cloud Functions 无法确认拉取订阅中的消息,因为它没有连接到它
    • 您的 Cloud Functions 处理并确认在其自己的订阅中发布的消息。

    【讨论】:

    • 感谢您对“主题”和“订阅”的澄清计数”减少?
    • 我更新了我的答案。查看您的订阅,您应该有 2 个
    • 哦,我终于明白了!来自 Push Subscription 的云功能 ACK 消息(您提到的“奇怪端点”)同时,相同的消息被发送到 Pull Subscription。所以我看到拉订阅的“未确认消息数”在增加。减少计数的一种方法是主动从 PubSub 中提取消息。 (我在本地尝试的示例代码)如果我错了,请纠正我。
    • 是的,正确。但是因为你已经处理了来自“推送”订阅的消息,你真的需要你的“拉取”订阅吗?
    • 你是对的。也许我应该删除那个订阅。
    猜你喜欢
    • 2018-07-15
    • 2021-07-04
    • 1970-01-01
    • 2017-11-14
    • 2017-11-10
    • 2019-09-19
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    相关资源
    最近更新 更多