如何使用 PUBSUB 作为触发器 return 来自 Google 云函数的 JSON?

How to return a JSON from Google Cloud functions using PUBSUB as trigger?

我正在使用 Python pubsub 客户端发布到主题,并且设置了一个由 pubsub 消息触发的云功能。我可以正确触发该功能并生成所需的 return 值,但我无法将 return 该值计算到 publisher/client 端。谢谢大家!

客户代码:

def call_getTime():

    message_future = publisher.publish(topic_path,
                                       data=data,
                                       )
    message_future.add_done_callback(callback)
    print(message_future.result())


def callback(message_future):
    if message_future.exception(timeout=30):
        print('Publishing message threw an Exception {}.'.format(
            message_future.exception()))
    else:
        print(message_future.result())

云函数:

def getTime(data, context):
        r = {'time': time.time()}
        return flask.jsonify(r)

Pubsub 函数不 "return" 消息。他们只是消费消息,他们通常不关心消息来自哪里。这不是一种双向通信形式。

如果您想要双向通信,请改用 HTTP 触发器。您可以在 HTTP 响应的正文中发回消息。

如果您出于某种原因不能使用 HTTP 而必须坚持使用 pubsub,请考虑将另一条消息发布到另一个主题,并安排发件人接收关于该另一个主题的消息。或者使用某种 webhook 通知某人消息已处理。