@@ -180,20 +180,28 @@ def publish_messages_with_batch_settings(project_id, topic_name):
180
180
# TODO project_id = "Your Google Cloud Project ID"
181
181
# TODO topic_name = "Your Pub/Sub topic name"
182
182
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.
185
185
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
187
189
)
188
190
publisher = pubsub_v1 .PublisherClient (batch_settings )
189
191
topic_path = publisher .topic_path (project_id , topic_name )
190
192
193
+ # Resolve the publish future in a separate thread.
194
+ def callback (future ):
195
+ message_id = future .result ()
196
+ print (message_id )
197
+
191
198
for n in range (1 , 10 ):
192
199
data = u"Message number {}" .format (n )
193
200
# Data must be a bytestring
194
201
data = data .encode ("utf-8" )
195
202
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 )
197
205
198
206
print ("Published messages with batch settings." )
199
207
# [END pubsub_publisher_batch_settings]
0 commit comments