我需要通过使用基于python的订阅服务器从googles Pub/Sub系统接收发布的消息。
为此,我执行了以下步骤:
gcloud pubsub subscriptions pull --auto-ack projects/{project_id}/subscriptions/{subscription_topic}在下面,您将看到我的代码的重要片段。它基于git示例,但在google-cloud-pubsub包的0.39.1版本中似乎不再存在一些函数。一个例子是subscriber.subscription_path()方法。
def receive_messages(subscription_path, service_account_json):
import time
from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient(credentials=service_account_json)
#subscription_path = subscriber.subscription_path(
# project_id, subscription_name)
def callback(message):
print('Received message: {}'.format(message))
message.ack()
subscriber.subscribe(subscription_path, callback=callback)
print('Listening for messages on {}'.format(subscription_path))
while True:
time.sleep(60)当我运行这个函数时,无数的线程在后台一点一点地启动,但似乎没有一个线程退出或启动回调函数。
pip3 freeze
asn1crypto==0.24.0
cachetools==3.0.0
certifi==2018.11.29
cffi==1.11.5
chardet==3.0.4
cryptography==2.4.2
google-api-core==1.7.0
google-api-python-client==1.7.5
google-auth==1.6.2
google-auth-httplib2==0.0.3
google-auth-oauthlib==0.2.0
google-cloud-bigquery==1.8.1
google-cloud-core==0.29.1
google-cloud-datastore==1.7.3
google-cloud-monitoring==0.31.1
google-cloud-pubsub==0.39.1
google-resumable-media==0.3.2
googleapis-common-protos==1.5.6
grpc-google-iam-v1==0.11.4
grpcio==1.17.1
httplib2==0.12.0
idna==2.8
keyring==10.1
keyrings.alt==1.3
oauthlib==3.0.0
paho-mqtt==1.4.0
protobuf==3.6.1
pyasn1==0.4.5
pyasn1-modules==0.2.3
pycparser==2.19
pycrypto==2.6.1
pycurl==7.43.0
pygobject==3.22.0
PyJWT==1.6.4
python-apt==1.4.0b3
pytz==2018.9
pyxdg==0.25
redis==3.0.1
requests==2.21.0
requests-oauthlib==1.2.0
RPi.GPIO==0.6.5
rsa==4.0
SecretStorage==2.3.1
six==1.12.0
unattended-upgrades==0.1
uritemplate==3.0.0
urllib3==1.24.1
virtualenv==16.2.0gcloud components update在过去的一周里,我一直在尝试不同的解决方案,或者开始一些看似过时的谷歌例子。此外,这些文档看起来甚至比代码示例还要老,对此并没有帮助。因此,我希望这里的人能够帮助我最终通过Pub/Sub-Sytsem接收基于python的客户端消息。
我希望我能提供最重要的信息,并感谢您为帮助我所做的努力。
发布于 2019-01-24 18:39:26
python文档站点这里上维护的示例应该是最新的。在运行任何代码之前,请确保您遵循了“为了使用此库,首先需要通过以下步骤”部分中的所有步骤。特别是,您可能没有正确设置身份验证,我不认为您应该手动传递凭据路径。
发布于 2021-11-22 22:11:29
def callback(message: pubsub_v1.subscriber.message.Message) -> None:
print(f"Received {message}.")
message.ack()
streaming_pull_future = subscriber.subscribe(subscription_path,
callback=callback)
print(f"Listening for messages on {subscription_path}..\n")
try:
streaming_pull_future.result(timeout=timeout)
except TimeoutError:
streaming_pull_future.cancel() # Trigger the shutdown.
streaming_pull_future.result() # Block until the shutdown is https://stackoverflow.com/questions/54197449
复制相似问题