首页 > 解决方案 > 如何处理错误或再次尝试使用 python 发布到 pubsub 消息谷歌

问题描述

我使用此脚本向 pubsub 中的主题发送消息:

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path("my-project", "my-topic")

while True:
    msg = b"some message"
    future = publisher.publish(topic_path, msg)

    try:
        result = future.result()
    except Exception as ex:
        # handle exception
        print(ex)

    time.sleep(3)

我的问题是当消息未在 pubsub 上发布时如何让我print(ex)打印或检测消息何时未发送并尝试再次发布。

标签: pythongoogle-cloud-pubsub

解决方案


您可以查看这篇文章,因为它为发布实现了错误处理。为获取回调创建了一个方法。它接受未来的对象和数据字符串。如果有异常,它将调用 exception() 以返回引发的异常。

def get_callback(f, data):
    def callback(f):
        try:
            print(f.result())
            futures.pop(data)
        except:  # noqa
            print("Please handle {} for {}.".format(f.exception(), data))

    return callback

该方法用于通过传递“future”和“data”参数来实现get_callback。其中future是一个对象,data是字符串。

for i in range(10):
    data = str(i)
    futures.update({data: None})
    # When you publish a message, the client returns a future.
    future = publisher.publish(topic_path, data.encode("utf-8"))
    futures[data] = future
    # Publish failures shall be handled in the callback function.
    future.add_done_callback(get_callback(future, data))
# Wait for all the publish futures to resolve before exiting.
while futures:
    time.sleep(5)

推荐阅读