所有
我正在尝试学习如何使用GCP PubSub,并且我能够通过CLI命令(创建主题,订阅,发布到主题,从订阅中提取等)进行测试,然而,当我跳到python(v 2.7,当前的公司标准)时,我正在努力以同步的方式提取消息。
我已经查看了这个网址,它会告诉你做一个睡眠而真实,但我无法想象有人在现实世界中这样做,对吗? https://cloud.google.com/pubsub/docs/quickstart-client-libraries#pubsub-subscribe-python
此网址告诉您可以使用我尝试过的future.result(),但它并不会像您一样阻止会话/线程: http://google-cloud-python.readthedocs.io/en/latest/pubsub/subscriber/index.html
谁有任何其他想法?这是我的功能,几乎是其中一个例子:def sample_receive_messages(subscription_name="my-sub", project=None):
"""Receives messages from a pull subscription."""
if not project:
credentials, project = google.auth.default()
subscriber = psub.SubscriberClient()
subscription_path = subscriber.subscription_path(
project, subscription_name)
def callback(message):
# print('Received message: {}'.format(message))
message.ack()
print('<message>' + str(message.data) + '</message>')
subscription = subscriber.subscribe(subscription_path)
future = subscription.open(callback)
myResult = future.result()
subscription.close()
print("done")
我最终的目标是让一个进程经常唤醒,抓取消息并确认消息,将消息写入文件,然后结束。
截至目前,该过程会读取消息并将其打印出来(很棒),然后它会坐下来坐下来,最后会出现一些乱码:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pubSubTools.py", line 50, in sample_receive_messages
myResult = future.result()
File "/usr/local/lib/python2.7/site-packages/google/cloud/pubsub_v1/futures.py", line 98, in result
raise err
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with (StatusCode.UNAVAILABLE, The service was unable to fulfill your request. Please try again. [code=8a75])>
答案 0 :(得分:1)
建议的实现是通过使用将来的回调来使用异步拉取。但是通过访问gapic库仍然可以实现同步拉动。
我使用Python 3.6运行它并使用google-cloud 0.32,因此它可能与Python 2.7略有不同。
from google.cloud.pubsub_v1.gapic.subscriber_client import SubscriberClient
pubsub_client = SubscriberClient()
subscription_path = 'projects/{project}/subscriptions/{subscription}'.format(project=project_name, subscription=subscription_name)
pull_response= pubsub_client.pull(subscription=subscription_path, max_messages=10)
for msg in pull_response.received_messages:
msg_id = msg.message.message_id
message = msg.message.data.decode('utf-8')
ack_id = msg.ack_id
如果类型为google.cloud.pubsub_v1.types.PullResponse,则为pull_response,您可以从pull_response.received_messages访问这些消息。
答案 1 :(得分:0)
Python库没有明确支持Cloud Pub / Sub API中的同步提取。 future.result()是阻塞的推荐方法,但它仍然是异步拉取的。
我建议您尝试使用官方Python Queue Class,其中回调调用Queue.put(),然后使用Queue.get()消耗消息。