如何查看Google Pub / Sub完成的时间

时间:2018-11-14 05:17:18

标签: python google-cloud-platform google-cloud-pubsub

从客户那里,我有以下代码:

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)
future = publisher.publish(topic_path, data=json.dumps(dict(op='create_master', review_id=1273612)))

有没有一种方法可以检查项目何时完成处理?如果是这样,那该怎么办?现在,我无法知道某人是否在“工作”。

2 个答案:

答案 0 :(得分:3)

要知道消息已成功发布,您需要查看将来的结果。首选方式是异步执行此操作:

def callback(future):
  try:
    print(future.result()) # future.result() is the message ID for the published message.
  except Exception as e:
    print("Error publishing: " + str(e))

future = publisher.publish(topic_path, data=json.dumps(dict(op='create_master', review_id=1273612)))
future.add_done_callback(callback)

如果需要,您也可以同步执行此操作。将来调用result()将会阻塞,直到发布结果可用为止。

future = publisher.publish(topic_path, data=json.dumps(dict(op='create_master', review_id=1273612)))
try:
  print(future.result()) # future.result() is the message ID for the published message.
except Exception as e:
  print("Error publishing: " + str(e))

没有内置的方式可以知道订户何时完成了对消息的处理。要求发布者知道订阅者何时处理了消息是一种反模式。发布者和订阅者旨在将彼此不直接了解的实体分开。就是说,如果您需要此类信息,则最好的方法是设置第二个主题,即原始订阅者在处理完原始发布者可以订阅的消息后发布消息,以便知道何时进行处理。完成。

答案 1 :(得分:0)

一种设置方法是将其存储在基于message_id的数据库中。例如,下面是一些示例服务器代码:

def callback(message):

    # Message has been received by the Server/Subscriber
    cursor.execute('INSERT IGNORE INTO pubsub (id, message, received) VALUES (%s, %s, NOW())', (message.message_id, message.data))
    connection.commit()

    # Message is processed by the Server/Subscriber
    data_obj = loads(message.data)
    _process(data_obj)

    # Message has finished being processed by the Server/Subscriber
    cursor.execute('UPDATE pubsub SET completed=NOW() WHERE id=%s', (message.message_id,))
    connection.commit()
    message.ack()

客户端可以通过id访问future.result(),因此可以轻松查询以查看其状态。如果在一个单独的进程中查看状态(例如,如果正在运行100个长期运行的进程,而我们要跟踪已完成的进程),这将特别有用。