diff --git a/pubsub/cloud-client/publisher.py b/pubsub/cloud-client/publisher.py index df7a9f23fd9..6802ec85fc1 100644 --- a/pubsub/cloud-client/publisher.py +++ b/pubsub/cloud-client/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]