Skip to content

Commit

Permalink
Pub/Sub: update publish with batch settings sample [(#3137)](GoogleCl…
Browse files Browse the repository at this point in the history
…oudPlatform/python-docs-samples#3137)

* non-blocking publish

* remove unused lib

* lint

* add defaults
  • Loading branch information
anguillanneuf authored and plamut committed Jul 10, 2020
1 parent 6c3f2fc commit b40267a
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions samples/snippets/publisher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit b40267a

Please sign in to comment.