|
| 1 | +/* |
| 2 | + * Copyright 2020 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package pubsub; |
| 18 | + |
| 19 | +// [START pubsub_quickstart_publisher] |
| 20 | + |
| 21 | +import com.google.api.core.ApiFuture; |
| 22 | +import com.google.cloud.pubsub.v1.Publisher; |
| 23 | +import com.google.protobuf.ByteString; |
| 24 | +import com.google.pubsub.v1.PubsubMessage; |
| 25 | +import com.google.pubsub.v1.TopicName; |
| 26 | +import java.io.IOException; |
| 27 | +import java.util.concurrent.ExecutionException; |
| 28 | +import java.util.concurrent.TimeUnit; |
| 29 | + |
| 30 | +public class PublisherExample { |
| 31 | + public static void main(String... args) throws Exception { |
| 32 | + // TODO(developer): Replace these variables before running the sample. |
| 33 | + String projectId = "your-project-id"; |
| 34 | + String topicId = "your-topic-id"; |
| 35 | + |
| 36 | + publisherExample(projectId, topicId); |
| 37 | + } |
| 38 | + |
| 39 | + public static void publisherExample(String projectId, String topicId) |
| 40 | + throws IOException, ExecutionException, InterruptedException { |
| 41 | + TopicName topicName = TopicName.of(projectId, topicId); |
| 42 | + |
| 43 | + Publisher publisher = null; |
| 44 | + try { |
| 45 | + // Create a publisher instance with default settings bound to the topic |
| 46 | + publisher = Publisher.newBuilder(topicName).build(); |
| 47 | + |
| 48 | + String message = "Hello World!"; |
| 49 | + ByteString data = ByteString.copyFromUtf8(message); |
| 50 | + PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); |
| 51 | + |
| 52 | + // Once published, returns a server-assigned message id (unique within the topic) |
| 53 | + ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage); |
| 54 | + String messageId = messageIdFuture.get(); |
| 55 | + System.out.println("Published message ID: " + messageId); |
| 56 | + } finally { |
| 57 | + if (publisher != null) { |
| 58 | + // When finished with the publisher, shutdown to free up resources. |
| 59 | + publisher.shutdown(); |
| 60 | + publisher.awaitTermination(1, TimeUnit.MINUTES); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | +// [END pubsub_quickstart_publisher] |
0 commit comments