Skip to content

Commit c0f6e6c

Browse files
Pub/Sub: update publish with batch settings sample (#3137)
* non-blocking publish * remove unused lib * lint * add defaults
1 parent 69da634 commit c0f6e6c

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

pubsub/cloud-client/publisher.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -180,20 +180,28 @@ def publish_messages_with_batch_settings(project_id, topic_name):
180180
# TODO project_id = "Your Google Cloud Project ID"
181181
# TODO topic_name = "Your Pub/Sub topic name"
182182

183-
# Configure the batch to publish as soon as there is one kilobyte
184-
# of data or one second has passed.
183+
# Configure the batch to publish as soon as there is ten messages,
184+
# one kilobyte of data, or one second has passed.
185185
batch_settings = pubsub_v1.types.BatchSettings(
186-
max_bytes=1024, max_latency=1 # One kilobyte # One second
186+
max_messages=10, # default 100
187+
max_bytes=1024, # default 1 MB
188+
max_latency=1, # default 10 ms
187189
)
188190
publisher = pubsub_v1.PublisherClient(batch_settings)
189191
topic_path = publisher.topic_path(project_id, topic_name)
190192

193+
# Resolve the publish future in a separate thread.
194+
def callback(future):
195+
message_id = future.result()
196+
print(message_id)
197+
191198
for n in range(1, 10):
192199
data = u"Message number {}".format(n)
193200
# Data must be a bytestring
194201
data = data.encode("utf-8")
195202
future = publisher.publish(topic_path, data=data)
196-
print(future.result())
203+
# Non-blocking. Allow the publisher client to batch multiple messages.
204+
future.add_done_callback(callback)
197205

198206
print("Published messages with batch settings.")
199207
# [END pubsub_publisher_batch_settings]

0 commit comments

Comments
 (0)