|
| 1 | +/* |
| 2 | + * Copyright 2017 Google Inc. All Rights Reserved. |
| 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 com.google.cloud.examples.pubsub; |
| 18 | + |
| 19 | +import com.google.api.gax.core.RpcFuture; |
| 20 | +import com.google.api.gax.core.RpcFutureCallback; |
| 21 | +import com.google.cloud.pubsub.spi.v1.Publisher; |
| 22 | +import com.google.protobuf.ByteString; |
| 23 | +import com.google.pubsub.v1.PubsubMessage; |
| 24 | +import com.google.pubsub.v1.TopicName; |
| 25 | +import java.util.ArrayList; |
| 26 | +import java.util.Arrays; |
| 27 | +import java.util.List; |
| 28 | + |
| 29 | +public class PublisherSnippets { |
| 30 | + /** |
| 31 | + * Example of publishing messages. |
| 32 | + */ |
| 33 | + // [TARGET publish(PubsubMessage)] |
| 34 | + // [VARIABLE "my_project_name"] |
| 35 | + // [VARIABLE "my_topic_name"] |
| 36 | + public void publish(String projectName, String topicName) throws Exception { |
| 37 | + // [START publish] |
| 38 | + Publisher publisher = Publisher.newBuilder(TopicName.create(projectName, topicName)).build(); |
| 39 | + List<String> messages = Arrays.asList("message1", "message2"); |
| 40 | + |
| 41 | + for (String message : messages) { |
| 42 | + ByteString data = ByteString.copyFromUtf8(message); |
| 43 | + PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); |
| 44 | + RpcFuture<String> messageIdFuture = publisher.publish(pubsubMessage); |
| 45 | + messageIdFuture.addCallback(new RpcFutureCallback<String>() { |
| 46 | + public void onSuccess(String messageId) { |
| 47 | + System.out.println("published with message id: " + messageId); |
| 48 | + } |
| 49 | + |
| 50 | + public void onFailure(Throwable t) { |
| 51 | + System.out.println("failed to publish: " + t); |
| 52 | + } |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + publisher.shutdown(); |
| 57 | + // [END publish] |
| 58 | + } |
| 59 | +} |
0 commit comments