我在Python客户端API中找不到 returnImmediately 标志。 这有什么具体原因吗? 还有另一种方法可以从Python中的订阅同步拉出排队的消息吗?
答案 0 :(得分:4)
Google不提供类似的内容。但您可以通过实现自己的队列
轻松解决此问题from Queue import Queue
from google.cloud import pubsub
subscriber = pubsub.SubscriberClient()
topic = "projects/newproject-xxxxx/topics/tarunlalwani"
subscription_name = 'projects/newproject-xxxxx/subscriptions/sub1'
class SynchronousSubscription(object):
def callback(self, message):
print(message.data)
message.ack()
self.pending_messages.put(message)
def __init__(self, subscription):
self.subscription_future = subscriber.subscribe(subscription_name, self.callback)
self.pending_messages = Queue()
def consume_sync(self):
return self.pending_messages.get()
sub = SynchronousSubscription(subscription_name)
data = sub.consume_sync()
当我测试时,它确实对我有用。
答案 1 :(得分:1)
扩展上一个答案:
目前存在具有所需功能的功能,以下是来自subscriber_client.py的文档:
def pull(self,
subscription,
max_messages,
return_immediately=None,
options=None):
...
Args:
...
return_immediately (bool): If this field set to true, the system
will respond immediately even if
it there are no messages available to return in the ``Pull`` response.
Otherwise, the system may wait (for a bounded amount of time) until at
least one message is available, rather than returning no messages. The
client may cancel the request if it does not wish to wait any longer for
the response.
但执行,首先读取this comment,返回两个例外(我提出的例外是两个例外):
RetryError(未分类的重试方法中发生异常 作为瞬态,由终止于的RPC的< _Rendezvous引起的 (StatusCode.INVALID_ARGUMENT,缺少必需参数 请求:(argument =“max_messages”)。)>)
如果您需要更多详细信息,可以related issue。
答案 2 :(得分:1)
Cloud Pub / Sub客户端库不直接公开pull方法,而是提供专为高效接收消息而设计的异步API。如果您有特定的理由想要调用同步拉方法(包括使用returnImmediately属性),那么您将需要生成基于gRPC的库。您需要获取service definition然后generate the client。或者,您可以使用REST API version of pull生成HTTP请求。
答案 3 :(得分:0)
Google云的上一个官方gcloud
python库(最新版本为0.18.3,pip提供) 对idiomatic python中的pull函数有稳定支持。虽然Cloud Pub / Sub API是GA,因此不推荐使用的库应该是稳定的,请注意此库不会获得任何更新。我在过去两年里广泛使用它而没有发生任何事故。
from gcloud import pubsub
# Connect to pubsub
client = pubsub.Client(project='myproject')
topic = client.topic('mytopic')
sub = topic.subscription('mysub')
if not topic.exists():
topic.create()
if not sub.exists():
sub.create()
# In your code, use a try-except for this pull and handle failures appropriately
recv = sub.pull(return_immediately=False, max_messages=1)
ack_id, msg = recv[0]
msg_attribute = msg.attributes['myattribute']
msg_data = msg.data
sub.acknowledge([ack_id, ])