Python中Google Cloud PubSub发布端代码卡住无响应求助
解决Google Cloud PubSub发布端卡住的问题
你的发布端代码卡在future.result()的原因是没有正确管理PublisherClient的生命周期,导致后台异步线程无法终止,程序一直等待资源释放。Google Cloud PubSub的Python客户端使用异步IO处理发布请求,若客户端未正确关闭,会残留未完成的线程,使程序无法正常退出。
修改后的发布端代码
import os from google.cloud import pubsub_v1 credentials_path = 'PATH/TO/THE/KEY.JSON' os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path # 使用with语句管理PublisherClient,自动处理关闭逻辑 with pubsub_v1.PublisherClient() as publisher: topic_path = 'projects/PROJECT_NAME/topics/TOPIC_NAME' data = 'A garden sensor is ready!' data = data.encode('utf-8') attributes = { 'sensorName': 'garden-001', 'temperature': '75.0', 'humidity': '60' } future = publisher.publish(topic_path, data, **attributes) print(f'published message id {future.result()}')
关键说明
with语句会在代码块执行完毕后自动调用publisher.close(),确保所有后台线程被正确终止,程序可以正常退出。- 若不想用
with,也可以在future.result()之后手动调用publisher.close(),但with是更规范的资源管理方式。 - 额外检查:确认服务账号拥有
pubsub.topics.publish权限(订阅端正常运行的话大概率没问题,若仍有异常可验证权限配置)。
内容的提问来源于stack exchange,提问作者bob
相关产品推荐
相关产品推荐

