在云函数中消费和解码 protobuf 消息

问题描述

我想使用来自主题(GCP 云发布/订阅)的发布/订阅消息,然后以某种方式加载到数据库中。

我决定创建一个云函数,其发布/订阅触发器连接到我想要从中消费消息的主题。数据以protobuf格式发送。

在编写一些 python 代码行时,我能够使用我的 .proto 文件解码消息并使用 'ParseFromString' 解析消息

import person_pb2 #This is the file generated from my .proto file with the format of the data

from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient()

    def callback(message):
        person = person_pb2.List()
        person.ParseFromString(message.data)
        print(person)
    
    future = subscriber.subscribe(f'projects/my_project/subscriptions/test-sub',callback)
    try:
        future.result()
    except KeyboardInterrupt:
        future.cancel()

下面是我的云函数中正在执行的函数。它目前正在运行,但正如您所看到的,我没有使用从我的 .proto 文件生成的 person_pb2。

def decode_pubsub(event,context):

    import base64

    print(f'message id: {context.event_id},timestamp: {context.timestamp}')
    data = event['data']
    decoded_data = base64.b64decode(data).decode('utf-8')
    print(decoded_data)

现在问题来了:

在第一个场景中,消息的类型是 我用 ParseFromString 解码 在第二种情况下,消息的类型是 我正在用 Base64 解码

云函数内是否不需要使用.proto文件来解码消息?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)