从订阅中拉取 Pub/Sub 消息

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

从现有 Pub/Sub 订阅持续拉取消息。

代码示例

Python

def main():
    """Continuously pull messages from subsciption"""
    client = pubsub.Client()
    subscription = client.topic(PUBSUB_TOPIC).subscription(PUBSUB_SUBSCRIPTION)

    print('Pulling messages from Pub/Sub subscription...')
    while True:
        with pubsub.subscription.AutoAck(subscription, max_messages=10) as ack:
            for _, message in list(ack.items()):
                print("[{0}] Received message: ID={1} Data={2}".format(
                    datetime.datetime.now(),
                    message.message_id,
                    message.data))
                process(message)

def process(message):
    """Process received message"""
    print("[{0}] Processing: {1}".format(datetime.datetime.now(),
                                         message.message_id))
    time.sleep(3)
    print("[{0}] Processed: {1}".format(datetime.datetime.now(),
                                        message.message_id))

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器