22
22
"""
23
23
24
24
import argparse
25
- import concurrent . futures
25
+ import time
26
26
27
27
from google .cloud import pubsub_v1
28
28
@@ -130,29 +130,27 @@ def publish_messages_with_error_handler(project, topic_name):
130
130
publisher = pubsub_v1 .PublisherClient ()
131
131
topic_path = publisher .topic_path (project , topic_name )
132
132
133
- # When you publish a message, the client returns a Future. This Future
134
- # can be used to track if an error has occurred.
135
- futures = []
136
-
137
- def callback (f ):
138
- exc = f .exception ()
139
- if exc :
133
+ def callback (message_future ):
134
+ if message_future .exception ():
140
135
print ('Publishing message on {} threw an Exception {}.' .format (
141
- topic_name , exc ))
136
+ topic_name , message_future .exception ()))
137
+ else :
138
+ print (message_future .result ())
142
139
143
140
for n in range (1 , 10 ):
144
141
data = u'Message number {}' .format (n )
145
142
# Data must be a bytestring
146
143
data = data .encode ('utf-8' )
144
+ # When you publish a message, the client returns a Future.
147
145
message_future = publisher .publish (topic_path , data = data )
148
146
message_future .add_done_callback (callback )
149
- futures .append (message_future )
147
+
148
+ print ('Published message IDs:' )
150
149
151
150
# We must keep the main thread from exiting to allow it to process
152
151
# messages in the background.
153
- concurrent .futures .wait (futures )
154
-
155
- print ('Published messages.' )
152
+ while True :
153
+ time .sleep (60 )
156
154
# [END pubsub_publish_messages_error_handler]
157
155
158
156
@@ -208,6 +206,11 @@ def publish_messages_with_batch_settings(project, topic_name):
208
206
help = publish_messages_with_futures .__doc__ )
209
207
publish_with_futures_parser .add_argument ('topic_name' )
210
208
209
+ publish_with_error_handler_parser = subparsers .add_parser (
210
+ 'publish-with-error-handler' ,
211
+ help = publish_messages_with_error_handler .__doc__ )
212
+ publish_with_error_handler_parser .add_argument ('topic_name' )
213
+
211
214
publish_with_batch_settings_parser = subparsers .add_parser (
212
215
'publish-with-batch-settings' ,
213
216
help = publish_messages_with_batch_settings .__doc__ )
@@ -227,5 +230,7 @@ def publish_messages_with_batch_settings(project, topic_name):
227
230
publish_messages_with_custom_attributes (args .project , args .topic_name )
228
231
elif args .command == 'publish-with-futures' :
229
232
publish_messages_with_futures (args .project , args .topic_name )
233
+ elif args .command == 'publish-with-error-handler' :
234
+ publish_messages_with_error_handler (args .project , args .topic_name )
230
235
elif args .command == 'publish-with-batch-settings' :
231
236
publish_messages_with_batch_settings (args .project , args .topic_name )
0 commit comments