|
1 | 1 | /* |
2 | | - Copyright 2016, Google, Inc. |
| 2 | + Copyright 2017, Google, Inc. |
3 | 3 |
|
4 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
5 | 5 | you may not use this file except in compliance with the License. |
|
18 | 18 |
|
19 | 19 | // [START pubsub_quickstart] |
20 | 20 | // Imports the Google Cloud client library |
21 | | -import com.google.cloud.pubsub.PubSub; |
22 | | -import com.google.cloud.pubsub.PubSubOptions; |
23 | | -import com.google.cloud.pubsub.Topic; |
24 | | -import com.google.cloud.pubsub.TopicInfo; |
25 | 21 |
|
26 | | -public class QuickstartSample { |
27 | | - public static void main(String... args) throws Exception { |
28 | | - // Instantiates a client |
29 | | - PubSub pubsub = PubSubOptions.getDefaultInstance().getService(); |
| 22 | +import com.google.api.gax.core.RpcFuture; |
| 23 | +import com.google.cloud.pubsub.spi.v1.Publisher; |
| 24 | +import com.google.cloud.pubsub.spi.v1.PublisherClient; |
| 25 | +import com.google.protobuf.ByteString; |
| 26 | +import com.google.pubsub.v1.PubsubMessage; |
| 27 | +import com.google.pubsub.v1.TopicName; |
30 | 28 |
|
31 | | - // The name for the new topic |
32 | | - String topicName = "my-new-topic"; |
| 29 | +public class QuickstartSample { |
33 | 30 |
|
34 | | - // Creates the new topic |
35 | | - Topic topic = pubsub.create(TopicInfo.of(topicName)); |
| 31 | + public static void main(String... args) throws Exception { |
36 | 32 |
|
37 | | - System.out.printf("Topic %s created.%n", topic.getName()); |
| 33 | + // Create a new topic |
| 34 | + String projectId = args[0]; |
| 35 | + TopicName topic = TopicName.create(projectId, "my-new-topic"); |
| 36 | + try (PublisherClient publisherClient = PublisherClient.create()) { |
| 37 | + publisherClient.createTopic(topic); |
| 38 | + } |
| 39 | + System.out.printf("Topic %s:%s created.\n", topic.getProject(), topic.getTopic()); |
| 40 | + |
| 41 | + // Creates a publisher |
| 42 | + Publisher publisher = null; |
| 43 | + try { |
| 44 | + publisher = Publisher.newBuilder(topic).build(); |
| 45 | + |
| 46 | + //Publish a message asynchronously |
| 47 | + String message = "my-message"; |
| 48 | + ByteString data = ByteString.copyFromUtf8(message); |
| 49 | + PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); |
| 50 | + RpcFuture<String> messageIdFuture = publisher.publish(pubsubMessage); |
| 51 | + |
| 52 | + //Print message id of published message |
| 53 | + System.out.println("published with message ID: " + messageIdFuture.get()); |
| 54 | + } finally { |
| 55 | + if (publisher != null) { |
| 56 | + publisher.shutdown(); |
| 57 | + } |
| 58 | + } |
38 | 59 | } |
39 | 60 | } |
40 | 61 | // [END pubsub_quickstart] |
0 commit comments