|
17 | 17 | package com.google.cloud.examples.pubsub.snippets; |
18 | 18 |
|
19 | 19 | import com.google.api.core.ApiFuture; |
| 20 | +import com.google.api.core.ApiFutureCallback; |
20 | 21 | import com.google.api.core.ApiFutures; |
| 22 | +import com.google.api.gax.rpc.ApiException; |
21 | 23 | import com.google.cloud.pubsub.v1.Publisher; |
22 | 24 | import com.google.cloud.pubsub.v1.TopicAdminClient; |
23 | 25 | import com.google.protobuf.ByteString; |
@@ -78,6 +80,54 @@ public static void publishMessages() throws Exception { |
78 | 80 | // [END pubsub_publish] |
79 | 81 | } |
80 | 82 |
|
| 83 | + public static void publishMessagesWithErrorHandler() throws Exception { |
| 84 | + // [START pubsub_publish_error_handler] |
| 85 | + ProjectTopicName topicName = ProjectTopicName.of("my-project-id", "my-topic-id"); |
| 86 | + Publisher publisher = null; |
| 87 | + |
| 88 | + try { |
| 89 | + // Create a publisher instance with default settings bound to the topic |
| 90 | + publisher = Publisher.newBuilder(topicName).build(); |
| 91 | + |
| 92 | + List<String> messages = Arrays.asList("first message", "second message"); |
| 93 | + |
| 94 | + for (final String message : messages) { |
| 95 | + ByteString data = ByteString.copyFromUtf8(message); |
| 96 | + PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); |
| 97 | + |
| 98 | + // Once published, returns a server-assigned message id (unique within the topic) |
| 99 | + ApiFuture<String> future = publisher.publish(pubsubMessage); |
| 100 | + |
| 101 | + // Add an asynchronous callback to handle success / failure |
| 102 | + ApiFutures.addCallback(future, new ApiFutureCallback<String>() { |
| 103 | + |
| 104 | + @Override |
| 105 | + public void onFailure(Throwable throwable) { |
| 106 | + if (throwable instanceof ApiException) { |
| 107 | + ApiException apiException = ((ApiException) throwable); |
| 108 | + // details on the API exception |
| 109 | + System.out.println(apiException.getStatusCode().getCode()); |
| 110 | + System.out.println(apiException.isRetryable()); |
| 111 | + } |
| 112 | + System.out.println("Error publishing message : " + message); |
| 113 | + } |
| 114 | + |
| 115 | + @Override |
| 116 | + public void onSuccess(String messageId) { |
| 117 | + // Once published, returns server-assigned message ids (unique within the topic) |
| 118 | + System.out.println(messageId); |
| 119 | + } |
| 120 | + }); |
| 121 | + } |
| 122 | + } finally { |
| 123 | + if (publisher != null) { |
| 124 | + // When finished with the publisher, shutdown to free up resources. |
| 125 | + publisher.shutdown(); |
| 126 | + } |
| 127 | + } |
| 128 | + // [END pubsub_publish_error_handler] |
| 129 | + } |
| 130 | + |
81 | 131 | public static void main(String... args) throws Exception { |
82 | 132 | createTopic(); |
83 | 133 | publishMessages(); |
|
0 commit comments