Search in sources :

Example 6 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project google-cloud-java by GoogleCloudPlatform.

the class CreateSubscriptionAndConsumeMessages method main.

public static void main(String... args) throws Exception {
    TopicName topic = TopicName.create("my-project-id", "my-topic-id");
    SubscriptionName subscription = SubscriptionName.create("my-project-id", "my-topic-id");
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
        subscriptionAdminClient.createSubscription(subscription, topic, PushConfig.getDefaultInstance(), 0);
    }
    MessageReceiver receiver = new MessageReceiver() {

        @Override
        public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
            System.out.println("Received message: " + message.getData().toStringUtf8());
            consumer.ack();
        }
    };
    Subscriber subscriber = null;
    try {
        subscriber = Subscriber.defaultBuilder(subscription, receiver).build();
        subscriber.addListener(new Subscriber.Listener() {

            @Override
            public void failed(Subscriber.State from, Throwable failure) {
                // Handle failure. This is called when the Subscriber encountered a fatal error and is shutting down.
                System.err.println(failure);
            }
        }, MoreExecutors.directExecutor());
        subscriber.startAsync().awaitRunning();
        Thread.sleep(60000);
    } finally {
        if (subscriber != null) {
            subscriber.stopAsync();
        }
    }
}
Also used : MessageReceiver(com.google.cloud.pubsub.spi.v1.MessageReceiver) Subscriber(com.google.cloud.pubsub.spi.v1.Subscriber) SubscriptionAdminClient(com.google.cloud.pubsub.spi.v1.SubscriptionAdminClient) SubscriptionName(com.google.pubsub.v1.SubscriptionName) AckReplyConsumer(com.google.cloud.pubsub.spi.v1.AckReplyConsumer) PubsubMessage(com.google.pubsub.v1.PubsubMessage) TopicName(com.google.pubsub.v1.TopicName)

Example 7 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project google-cloud-java by GoogleCloudPlatform.

the class CreateTopicAndPublishMessages method publishMessages.

public static void publishMessages() throws Exception {
    // [START pubsub_publish]
    TopicName topicName = TopicName.create("my-project-id", "my-topic-id");
    Publisher publisher = null;
    List<ApiFuture<String>> messageIdFutures = new ArrayList<>();
    try {
        // Create a publisher instance with default settings bound to the topic
        publisher = Publisher.defaultBuilder(topicName).build();
        List<String> messages = Arrays.asList("first message", "second message");
        // schedule publishing one message at a time : messages get automatically batched
        for (String message : messages) {
            ByteString data = ByteString.copyFromUtf8(message);
            PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
            // Once published, returns a server-assigned message id (unique within the topic)
            ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
            messageIdFutures.add(messageIdFuture);
        }
    } finally {
        // wait on any pending publish requests.
        List<String> messageIds = ApiFutures.allAsList(messageIdFutures).get();
        for (String messageId : messageIds) {
            System.out.println("published with message ID: " + messageId);
        }
        if (publisher != null) {
            // When finished with the publisher, shutdown to free up resources.
            publisher.shutdown();
        }
    }
// [END pubsub_publish]
}
Also used : ApiFuture(com.google.api.core.ApiFuture) ByteString(com.google.protobuf.ByteString) ArrayList(java.util.ArrayList) Publisher(com.google.cloud.pubsub.spi.v1.Publisher) ByteString(com.google.protobuf.ByteString) PubsubMessage(com.google.pubsub.v1.PubsubMessage) TopicName(com.google.pubsub.v1.TopicName)

Example 8 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project google-cloud-java by GoogleCloudPlatform.

the class PublisherSnippets method publish.

/** Example of publishing a message. */
// [TARGET publish(PubsubMessage)]
// [VARIABLE "my_message"]
public ApiFuture<String> publish(String message) {
    ByteString data = ByteString.copyFromUtf8(message);
    PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
    ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
    ApiFutures.addCallback(messageIdFuture, new ApiFutureCallback<String>() {

        public void onSuccess(String messageId) {
            System.out.println("published with message id: " + messageId);
        }

        public void onFailure(Throwable t) {
            System.out.println("failed to publish: " + t);
        }
    });
    return messageIdFuture;
}
Also used : ByteString(com.google.protobuf.ByteString) ByteString(com.google.protobuf.ByteString) PubsubMessage(com.google.pubsub.v1.PubsubMessage)

Example 9 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project beam by apache.

the class PubsubGrpcClientTest method publishOneMessage.

@Test
public void publishOneMessage() throws IOException {
    String expectedTopic = TOPIC.getPath();
    PubsubMessage expectedPubsubMessage = PubsubMessage.newBuilder().setData(ByteString.copyFrom(DATA.getBytes())).putAllAttributes(ATTRIBUTES).putAllAttributes(ImmutableMap.of(TIMESTAMP_ATTRIBUTE, String.valueOf(MESSAGE_TIME), ID_ATTRIBUTE, RECORD_ID)).build();
    final PublishRequest expectedRequest = PublishRequest.newBuilder().setTopic(expectedTopic).addAllMessages(ImmutableList.of(expectedPubsubMessage)).build();
    final PublishResponse response = PublishResponse.newBuilder().addAllMessageIds(ImmutableList.of(MESSAGE_ID)).build();
    final List<PublishRequest> requestsReceived = new ArrayList<>();
    PublisherImplBase publisherImplBase = new PublisherImplBase() {

        @Override
        public void publish(PublishRequest request, StreamObserver<PublishResponse> responseObserver) {
            requestsReceived.add(request);
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    };
    Server server = InProcessServerBuilder.forName(channelName).addService(publisherImplBase).build().start();
    try {
        OutgoingMessage actualMessage = new OutgoingMessage(DATA.getBytes(), ATTRIBUTES, MESSAGE_TIME, RECORD_ID);
        int n = client.publish(TOPIC, ImmutableList.of(actualMessage));
        assertEquals(1, n);
        assertEquals(expectedRequest, Iterables.getOnlyElement(requestsReceived));
    } finally {
        server.shutdownNow();
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) PublishResponse(com.google.pubsub.v1.PublishResponse) OutgoingMessage(org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.OutgoingMessage) Server(io.grpc.Server) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) PublishRequest(com.google.pubsub.v1.PublishRequest) PubsubMessage(com.google.pubsub.v1.PubsubMessage) PublisherImplBase(com.google.pubsub.v1.PublisherGrpc.PublisherImplBase) Test(org.junit.Test)

Example 10 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project google-cloud-java by GoogleCloudPlatform.

the class SubscriberSnippets method createSubscriber.

private void createSubscriber() throws Exception {
    // [START pubsub_pull]
    String projectId = "my-project-id";
    String subscriptionId = "my-subscription-id";
    SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
    // Instantiate an asynchronous message receiver
    MessageReceiver receiver = new MessageReceiver() {

        @Override
        public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
            // handle incoming message, then ack/nack the received message
            System.out.println("Id : " + message.getMessageId());
            System.out.println("Data : " + message.getData().toStringUtf8());
            consumer.ack();
        }
    };
    Subscriber subscriber = null;
    try {
        // Create a subscriber for "my-subscription-id" bound to the message receiver
        subscriber = Subscriber.defaultBuilder(subscriptionName, receiver).build();
        subscriber.startAsync();
    // ...
    } finally {
        // stop receiving messages
        if (subscriber != null) {
            subscriber.stopAsync();
        }
    }
// [END pubsub_pull]
}
Also used : MessageReceiver(com.google.cloud.pubsub.spi.v1.MessageReceiver) Subscriber(com.google.cloud.pubsub.spi.v1.Subscriber) SubscriptionName(com.google.pubsub.v1.SubscriptionName) AckReplyConsumer(com.google.cloud.pubsub.spi.v1.AckReplyConsumer) PubsubMessage(com.google.pubsub.v1.PubsubMessage)

Aggregations

PubsubMessage (com.google.pubsub.v1.PubsubMessage)12 ByteString (com.google.protobuf.ByteString)7 TopicName (com.google.pubsub.v1.TopicName)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 AckReplyConsumer (com.google.cloud.pubsub.spi.v1.AckReplyConsumer)3 MessageReceiver (com.google.cloud.pubsub.spi.v1.MessageReceiver)3 Publisher (com.google.cloud.pubsub.spi.v1.Publisher)3 Subscriber (com.google.cloud.pubsub.spi.v1.Subscriber)3 SubscriptionName (com.google.pubsub.v1.SubscriptionName)3 Timestamp (com.google.protobuf.Timestamp)2 PublishRequest (com.google.pubsub.v1.PublishRequest)2 PublishResponse (com.google.pubsub.v1.PublishResponse)2 PullRequest (com.google.pubsub.v1.PullRequest)2 PullResponse (com.google.pubsub.v1.PullResponse)2 ReceivedMessage (com.google.pubsub.v1.ReceivedMessage)2 Server (io.grpc.Server)2 StreamObserver (io.grpc.stub.StreamObserver)2 ApiFuture (com.google.api.core.ApiFuture)1 FlowControlException (com.google.api.gax.batching.FlowController.FlowControlException)1