18
18
// [START pubsub_quickstart_publisher]
19
19
20
20
import com .google .api .core .ApiFuture ;
21
- import com .google .api .core .ApiFutureCallback ;
22
21
import com .google .api .core .ApiFutures ;
23
- import com .google .api .gax .rpc .ApiException ;
24
22
import com .google .cloud .ServiceOptions ;
25
23
import com .google .cloud .pubsub .v1 .Publisher ;
26
24
import com .google .protobuf .ByteString ;
27
25
import com .google .pubsub .v1 .ProjectTopicName ;
28
26
import com .google .pubsub .v1 .PubsubMessage ;
29
27
28
+ import java .util .ArrayList ;
29
+ import java .util .Arrays ;
30
+ import java .util .List ;
31
+
30
32
public class PublisherExample {
31
33
32
34
// use the default project id
@@ -41,6 +43,8 @@ public static void main(String... args) throws Exception {
41
43
int messageCount = Integer .parseInt (args [1 ]);
42
44
ProjectTopicName topicName = ProjectTopicName .of (PROJECT_ID , topicId );
43
45
Publisher publisher = null ;
46
+ List <ApiFuture <String >> futures = new ArrayList <>();
47
+
44
48
try {
45
49
// Create a publisher instance with default settings bound to the topic
46
50
publisher = Publisher .newBuilder (topicName ).build ();
@@ -54,31 +58,18 @@ public static void main(String... args) throws Exception {
54
58
.setData (data )
55
59
.build ();
56
60
57
- //schedule a message to be published, messages are automatically batched
61
+ // Schedule a message to be published. Messages are automatically batched.
58
62
ApiFuture <String > future = publisher .publish (pubsubMessage );
59
-
60
- // add an asynchronous callback to handle success / failure
61
- ApiFutures .addCallback (future , new ApiFutureCallback <String >() {
62
-
63
- @ Override
64
- public void onFailure (Throwable throwable ) {
65
- if (throwable instanceof ApiException ) {
66
- ApiException apiException = ((ApiException ) throwable );
67
- // details on the API exception
68
- System .out .println (apiException .getStatusCode ().getCode ());
69
- System .out .println (apiException .isRetryable ());
70
- }
71
- System .out .println ("Error publishing message : " + message );
72
- }
73
-
74
- @ Override
75
- public void onSuccess (String messageId ) {
76
- // Once published, returns server-assigned message ids (unique within the topic)
77
- System .out .println (messageId );
78
- }
79
- });
63
+ futures .add (future );
80
64
}
81
65
} finally {
66
+ // Wait on any pending requests
67
+ List <String > messageIds = ApiFutures .allAsList (futures ).get ();
68
+
69
+ for (String messageId : messageIds ) {
70
+ System .out .println (messageId );
71
+ }
72
+
82
73
if (publisher != null ) {
83
74
// When finished with the publisher, shutdown to free up resources.
84
75
publisher .shutdown ();
0 commit comments