Skip to content

Commit 059bb0e

Browse files
authored
updating pub/sub samples (GoogleCloudPlatform#928)
* updating pub/sub samples * another update
1 parent 04ffdf0 commit 059bb0e

File tree

6 files changed

+62
-36
lines changed

6 files changed

+62
-36
lines changed

flexible/pubsub/src/main/java/com/example/flexible/pubsub/PubSubPublish.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp)
3939
String topicId = System.getenv("PUBSUB_TOPIC");
4040
// create a publisher on the topic
4141
if (publisher == null) {
42-
publisher = Publisher.defaultBuilder(
43-
TopicName.create(ServiceOptions.getDefaultProjectId(), topicId))
42+
publisher = Publisher.newBuilder(
43+
TopicName.of(ServiceOptions.getDefaultProjectId(), topicId))
4444
.build();
4545
}
4646
// construct a pubsub message from the payload

pubsub/cloud-client/src/main/java/com/example/pubsub/CreatePullSubscriptionExample.java

+7-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package com.example.pubsub;
1818

1919
// [START pubsub_quickstart_create_subscription]
20+
import com.google.api.gax.rpc.ApiException;
2021
import com.google.cloud.ServiceOptions;
2122
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
2223
import com.google.pubsub.v1.PushConfig;
@@ -43,15 +44,19 @@ public static void main(String... args) throws Exception {
4344
// Your subscription ID eg. "my-sub"
4445
String subscriptionId = args[1];
4546

46-
TopicName topicName = TopicName.create(projectId, topicId);
47+
TopicName topicName = TopicName.of(projectId, topicId);
4748

4849
// Create a new subscription
49-
SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
50+
SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
5051
try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
5152
// create a pull subscription with default acknowledgement deadline (= 10 seconds)
5253
Subscription subscription =
5354
subscriptionAdminClient.createSubscription(
5455
subscriptionName, topicName, PushConfig.getDefaultInstance(), 0);
56+
} catch (ApiException e) {
57+
// example : code = ALREADY_EXISTS(409) implies subscription already exists
58+
System.out.print(e.getStatusCode().getCode());
59+
System.out.print(e.isRetryable());
5560
}
5661

5762
System.out.printf(

pubsub/cloud-client/src/main/java/com/example/pubsub/CreateTopicExample.java

+6-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
// [START pubsub_quickstart_create_topic]
2020
// Imports the Google Cloud client library
21+
import com.google.api.gax.rpc.ApiException;
2122
import com.google.cloud.ServiceOptions;
2223
import com.google.cloud.pubsub.v1.TopicAdminClient;
2324
import com.google.pubsub.v1.TopicName;
@@ -39,9 +40,13 @@ public static void main(String... args) throws Exception {
3940
String topicId = args[0];
4041

4142
// Create a new topic
42-
TopicName topic = TopicName.create(projectId, topicId);
43+
TopicName topic = TopicName.of(projectId, topicId);
4344
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
4445
topicAdminClient.createTopic(topic);
46+
} catch (ApiException e) {
47+
// example : code = ALREADY_EXISTS(409) implies topic already exists
48+
System.out.print(e.getStatusCode().getCode());
49+
System.out.print(e.isRetryable());
4550
}
4651

4752
System.out.printf("Topic %s:%s created.\n", topic.getProject(), topic.getTopic());

pubsub/cloud-client/src/main/java/com/example/pubsub/PublisherExample.java

+40-25
Original file line numberDiff line numberDiff line change
@@ -18,52 +18,67 @@
1818
// [START pubsub_quickstart_publisher]
1919

2020
import com.google.api.core.ApiFuture;
21+
import com.google.api.core.ApiFutureCallback;
2122
import com.google.api.core.ApiFutures;
23+
import com.google.api.gax.rpc.ApiException;
2224
import com.google.cloud.ServiceOptions;
2325
import com.google.cloud.pubsub.v1.Publisher;
2426
import com.google.protobuf.ByteString;
2527
import com.google.pubsub.v1.PubsubMessage;
2628
import com.google.pubsub.v1.TopicName;
27-
import java.util.ArrayList;
28-
import java.util.List;
2929

3030
public class PublisherExample {
3131

32-
static final int MESSAGE_COUNT = 5;
33-
3432
// use the default project id
3533
private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId();
3634

37-
//schedule a message to be published, messages are automatically batched
38-
private static ApiFuture<String> publishMessage(Publisher publisher, String message)
39-
throws Exception {
40-
// convert message to bytes
41-
ByteString data = ByteString.copyFromUtf8(message);
42-
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
43-
return publisher.publish(pubsubMessage);
44-
}
45-
46-
/** Publish messages to a topic. */
35+
/** Publish messages to a topic.
36+
* @param args topic name, number of messages
37+
*/
4738
public static void main(String... args) throws Exception {
4839
// topic id, eg. "my-topic"
4940
String topicId = args[0];
50-
TopicName topicName = TopicName.create(PROJECT_ID, topicId);
41+
int messageCount = Integer.parseInt(args[1]);
42+
TopicName topicName = TopicName.of(PROJECT_ID, topicId);
5143
Publisher publisher = null;
52-
List<ApiFuture<String>> apiFutures = new ArrayList<>();
5344
try {
5445
// Create a publisher instance with default settings bound to the topic
55-
publisher = Publisher.defaultBuilder(topicName).build();
56-
for (int i = 0; i < MESSAGE_COUNT; i++) {
46+
publisher = Publisher.newBuilder(topicName).build();
47+
48+
for (int i = 0; i < messageCount; i++) {
5749
String message = "message-" + i;
58-
ApiFuture<String> messageId = publishMessage(publisher, message);
59-
apiFutures.add(messageId);
50+
51+
// convert message to bytes
52+
ByteString data = ByteString.copyFromUtf8(message);
53+
PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
54+
.setData(data)
55+
.build();
56+
57+
//schedule a message to be published, messages are automatically batched
58+
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+
});
6080
}
6181
} finally {
62-
// Once published, returns server-assigned message ids (unique within the topic)
63-
List<String> messageIds = ApiFutures.allAsList(apiFutures).get();
64-
for (String messageId : messageIds) {
65-
System.out.println(messageId);
66-
}
6782
if (publisher != null) {
6883
// When finished with the publisher, shutdown to free up resources.
6984
publisher.shutdown();

pubsub/cloud-client/src/main/java/com/example/pubsub/SubscriberExample.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,12 @@ public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
4747
public static void main(String... args) throws Exception {
4848
// set subscriber id, eg. my-sub
4949
String subscriptionId = args[0];
50-
SubscriptionName subscriptionName = SubscriptionName.create(PROJECT_ID, subscriptionId);
50+
SubscriptionName subscriptionName = SubscriptionName.of(PROJECT_ID, subscriptionId);
5151
Subscriber subscriber = null;
5252
try {
5353
// create a subscriber bound to the asynchronous message receiver
5454
subscriber =
55-
Subscriber.defaultBuilder(subscriptionName, new MessageReceiverExample()).build();
55+
Subscriber.newBuilder(subscriptionName, new MessageReceiverExample()).build();
5656
subscriber.startAsync().awaitRunning();
5757
// Continue to listen to messages
5858
while (true) {

pubsub/cloud-client/src/test/java/com/example/pubsub/QuickStartIT.java

+5-4
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ public class QuickStartIT {
4949
private String projectId = ServiceOptions.getDefaultProjectId();
5050
private String topicId = formatForTest("my-topic");
5151
private String subscriptionId = formatForTest("my-sub");
52+
private int messageCount = 5;
5253

5354
class SubscriberRunnable implements Runnable {
5455

@@ -104,9 +105,9 @@ public void testQuickstart() throws Exception {
104105

105106
bout.reset();
106107
// publish messages
107-
PublisherExample.main(topicId);
108+
PublisherExample.main(topicId, String.valueOf(messageCount));
108109
String[] messageIds = bout.toString().split("\n");
109-
assertThat(messageIds).hasLength(PublisherExample.MESSAGE_COUNT);
110+
assertThat(messageIds).hasLength(messageCount);
110111

111112
bout.reset();
112113
// receive messages
@@ -132,7 +133,7 @@ private String formatForTest(String name) {
132133

133134
private void deleteTestTopic() throws Exception {
134135
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
135-
topicAdminClient.deleteTopic(TopicName.create(projectId, topicId));
136+
topicAdminClient.deleteTopic(TopicName.of(projectId, topicId));
136137
} catch (IOException e) {
137138
System.err.println("Error deleting topic " + e.getMessage());
138139
}
@@ -141,7 +142,7 @@ private void deleteTestTopic() throws Exception {
141142
private void deleteTestSubscription() throws Exception {
142143
try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
143144
subscriptionAdminClient.deleteSubscription(
144-
SubscriptionName.create(projectId, subscriptionId));
145+
SubscriptionName.of(projectId, subscriptionId));
145146
} catch (IOException e) {
146147
System.err.println("Error deleting subscription " + e.getMessage());
147148
}

0 commit comments

Comments
 (0)