繁体   English   中英

GCP Cloud Function 未正确拾取/确认 PubSub 消息

[英]GCP Cloud Function not correctly picking up/acknowledging PubSub messages

我在 Google Cloud Platform 中设置了一些数据处理工作流程。 这些位置处理物理地址并返回一些关于它们的指标。 工作流使用 Cloud Functions 和 PubSub 流的组合。

在工作流中使用一个 Google Cloud Function 时,某些消息不会从触发 stream 中拾取或被多次拾取。 我知道这在一定程度上是可以预料的。 但是,这种情况经常发生。 这足以导致某些地点被夸大 10 倍,而其他几个地点却没有结果。

我认为callback function 没有正确确认消息,但我不确定要获得更可靠的消息接收和确认应该有什么不同。 任何建议表示赞赏。

My GCP Cloud Function to retrieve metrics is triggered by a PubSub stream and executes the retrieve_location function sending data to a different PubSub stream. retrieve_location位置 function 如下所示:

def retrieve_location(event, context):
    auth_flow()

    project_id = <my project id>
    subscription_name = <my subscription name>

    subscriber = pubsub_v1.SubscriberClient()

    subscription_path = subscriber.subscription_path(
        project_id, subscription_name)

    def callback(message):
        message.ack()
        message_obj = message.data
        message_dcde = message_obj.decode('utf-8')
        message_json = json.loads(message_dcde)

        get_metrics(message_json)


    subscriber.subscribe(subscription_path, callback=callback)

get_metrics function 从每条消息中获取有效负载,检索一些数据并将其发送到另一个 stream。 这个 function 似乎按预期工作。

def get_metrics(loc):
    <... retrieve and process data, my_data is the object that gets sent to the next stream ...>
          project_id = <my project id>
          topic_name = <my topic name>
          topic_id = <my topic id>

          publisher = pubsub_v1.PublisherClient()
          topic_path = publisher.topic_path(project_id, topic_name)

            try:
                publisher.publish(topic_path, data=my_data.encode('utf-8'))
            except Exception as exc:
                    print("topic publish failed: ", exc)

而不是在您的 Cloud Function 中设置第二个 Pub/Sub 订阅者,您应该创建一个后台 function来订阅直接处理有效负载的主题,例如:

def get_metrics_background_function(event, context):
    message_obj = event.data
    message_dcde = message_obj.decode('utf-8')
    message_json = json.loads(message_dcde)

    get_metrics(message_json)

看起来您可能会将使用 Cloud Pub/Sub 来触发 Cloud Function 与直接通过 Cloud Pub/Sub 客户端库使用 Pub/Sub 混为一谈。 一般来说,你会想要做一个或另一个。

如果您创建的订阅是通过 Cloud Functions 完成的,那么您的retrieve_location function 并没有真正接收和处理消息。 相反,它正在做的是启动一个订阅者客户端并在此后不久关闭,因为subscriber.subscribe将运行完成,因此您的 function 将完成执行。

If this function is starting up a client to the same subscription that triggers the Cloud Function, then it isn't actually going to do anything because Cloud-Function-based subscriptions use the push model while the client library should be used with the pull model .

您要么想要直接在retrieve_location中执行callback中的操作,使用事件作为消息(如Dustin 所述),要么您想要使用客户端库设置一个持久订阅者,例如在GCE 上,实例化订阅者并调用subscribe它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM