【发布时间】: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