From b40267a539c3313c79944a97eb4522a41404d5bb Mon Sep 17 00:00:00 2001 From: Tianzi Cai Date: Wed, 25 Mar 2020 12:47:33 -0700 Subject: [PATCH] Pub/Sub: update publish with batch settings sample [(#3137)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3137) * non-blocking publish * remove unused lib * lint * add defaults --- samples/snippets/publisher.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/samples/snippets/publisher.py b/samples/snippets/publisher.py index df7a9f23f..6802ec85f 100644 --- a/samples/snippets/publisher.py +++ b/samples/snippets/publisher.py @@ -180,20 +180,28 @@ def publish_messages_with_batch_settings(project_id, topic_name): # TODO project_id = "Your Google Cloud Project ID" # TODO topic_name = "Your Pub/Sub topic name" - # Configure the batch to publish as soon as there is one kilobyte - # of data or one second has passed. + # Configure the batch to publish as soon as there is ten messages, + # one kilobyte of data, or one second has passed. batch_settings = pubsub_v1.types.BatchSettings( - max_bytes=1024, max_latency=1 # One kilobyte # One second + max_messages=10, # default 100 + max_bytes=1024, # default 1 MB + max_latency=1, # default 10 ms ) publisher = pubsub_v1.PublisherClient(batch_settings) topic_path = publisher.topic_path(project_id, topic_name) + # Resolve the publish future in a separate thread. + def callback(future): + message_id = future.result() + print(message_id) + for n in range(1, 10): data = u"Message number {}".format(n) # Data must be a bytestring data = data.encode("utf-8") future = publisher.publish(topic_path, data=data) - print(future.result()) + # Non-blocking. Allow the publisher client to batch multiple messages. + future.add_done_callback(callback) print("Published messages with batch settings.") # [END pubsub_publisher_batch_settings]