Search in sources :

Example 1 with MessageReceiver

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

the class ITPubSubTest method testPublishSubscribe.

@Test
public void testPublishSubscribe() throws Exception {
    TopicName topicName = TopicName.create(projectId, formatForTest("testing-publish-subscribe-topic"));
    SubscriptionName subscriptionName = SubscriptionName.create(projectId, formatForTest("testing-publish-subscribe-subscription"));
    topicAdminClient.createTopic(topicName);
    subscriptionAdminClient.createSubscription(subscriptionName, topicName, PushConfig.newBuilder().build(), 10);
    PubsubMessage message = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8("my message")).build();
    final SettableApiFuture<PubsubMessage> received = SettableApiFuture.create();
    Subscriber subscriber = Subscriber.defaultBuilder(subscriptionName, new MessageReceiver() {

        @Override
        public void receiveMessage(final PubsubMessage message, final AckReplyConsumer consumer) {
            if (received.set(message)) {
                consumer.ack();
            } else {
                consumer.nack();
            }
        }
    }).build();
    subscriber.addListener(new Subscriber.Listener() {

        public void failed(Subscriber.State from, Throwable failure) {
            received.setException(failure);
        }
    }, MoreExecutors.directExecutor());
    subscriber.startAsync();
    Publisher publisher = Publisher.defaultBuilder(topicName).build();
    publisher.publish(message).get();
    publisher.shutdown();
    assertEquals(received.get().getData(), message.getData());
    subscriber.stopAsync().awaitTerminated();
    subscriptionAdminClient.deleteSubscription(subscriptionName);
    topicAdminClient.deleteTopic(topicName);
}
Also used : Subscriber(com.google.cloud.pubsub.spi.v1.Subscriber) MessageReceiver(com.google.cloud.pubsub.spi.v1.MessageReceiver) SubscriptionName(com.google.pubsub.v1.SubscriptionName) Publisher(com.google.cloud.pubsub.spi.v1.Publisher) AckReplyConsumer(com.google.cloud.pubsub.spi.v1.AckReplyConsumer) PubsubMessage(com.google.pubsub.v1.PubsubMessage) TopicName(com.google.pubsub.v1.TopicName) Test(org.junit.Test)

Example 2 with MessageReceiver

use of com.google.cloud.pubsub.v1.MessageReceiver 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 3 with MessageReceiver

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

the class TestPubsubSignal method pollForResultForDuration.

private String pollForResultForDuration(SubscriptionPath signalSubscriptionPath, Duration timeoutDuration) throws IOException {
    AtomicReference<String> result = new AtomicReference<>(null);
    MessageReceiver receiver = (com.google.pubsub.v1.PubsubMessage message, AckReplyConsumer replyConsumer) -> {
        LOG.info("Received message: {}", message.getData().toStringUtf8());
        // Ignore empty messages
        if (message.getData().isEmpty()) {
            replyConsumer.ack();
        }
        if (result.compareAndSet(null, message.getData().toStringUtf8())) {
            replyConsumer.ack();
        } else {
            replyConsumer.nack();
        }
    };
    Subscriber subscriber = Subscriber.newBuilder(signalSubscriptionPath.getPath(), receiver).setCredentialsProvider(pipelineOptions::getGcpCredential).setEndpoint(pubsubEndpoint).build();
    subscriber.startAsync();
    DateTime startTime = new DateTime();
    int timeoutSeconds = timeoutDuration.toStandardSeconds().getSeconds();
    while (result.get() == null && Seconds.secondsBetween(startTime, new DateTime()).getSeconds() < timeoutSeconds) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignored) {
        }
    }
    subscriber.stopAsync();
    subscriber.awaitTerminated();
    if (result.get() == null) {
        throw new AssertionError(String.format("Did not receive signal on %s in %ss", signalSubscriptionPath, timeoutDuration.getStandardSeconds()));
    }
    return result.get();
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) DateTime(org.joda.time.DateTime) MessageReceiver(com.google.cloud.pubsub.v1.MessageReceiver) Subscriber(com.google.cloud.pubsub.v1.Subscriber) AckReplyConsumer(com.google.cloud.pubsub.v1.AckReplyConsumer)

Example 4 with MessageReceiver

use of com.google.cloud.pubsub.v1.MessageReceiver 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)

Example 5 with MessageReceiver

use of com.google.cloud.pubsub.v1.MessageReceiver in project spring-cloud-gcp by spring-cloud.

the class PubSubTemplate method subscribe.

@Override
public Subscriber subscribe(String subscription, MessageReceiver messageHandler) {
    Subscriber subscriber = this.subscriberFactory.createSubscriber(subscription, messageHandler);
    subscriber.startAsync();
    return subscriber;
}
Also used : Subscriber(com.google.cloud.pubsub.v1.Subscriber)

Aggregations

Subscriber (com.google.cloud.pubsub.v1.Subscriber)4 AckReplyConsumer (com.google.cloud.pubsub.spi.v1.AckReplyConsumer)3 MessageReceiver (com.google.cloud.pubsub.spi.v1.MessageReceiver)3 Subscriber (com.google.cloud.pubsub.spi.v1.Subscriber)3 PubsubMessage (com.google.pubsub.v1.PubsubMessage)3 SubscriptionName (com.google.pubsub.v1.SubscriptionName)3 AckReplyConsumer (com.google.cloud.pubsub.v1.AckReplyConsumer)2 MessageReceiver (com.google.cloud.pubsub.v1.MessageReceiver)2 TopicName (com.google.pubsub.v1.TopicName)2 ApiFuture (com.google.api.core.ApiFuture)1 ApiFutures (com.google.api.core.ApiFutures)1 GrpcTransportChannel (com.google.api.gax.grpc.GrpcTransportChannel)1 FixedTransportChannelProvider (com.google.api.gax.rpc.FixedTransportChannelProvider)1 TransportChannelProvider (com.google.api.gax.rpc.TransportChannelProvider)1 Publisher (com.google.cloud.pubsub.spi.v1.Publisher)1 SubscriptionAdminClient (com.google.cloud.pubsub.spi.v1.SubscriptionAdminClient)1 Publisher (com.google.cloud.pubsub.v1.Publisher)1 SubscriptionAdminClient (com.google.cloud.pubsub.v1.SubscriptionAdminClient)1 SubscriptionAdminSettings (com.google.cloud.pubsub.v1.SubscriptionAdminSettings)1 TopicAdminClient (com.google.cloud.pubsub.v1.TopicAdminClient)1