示例#1
0
    public Subscription CreateSubscriptionWithDeadLetterPolicy(string projectId, string subscriptionId, string topicId, string deadLetterTopicId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        // This is the subscription you want to create with a dead letter policy.
        var subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        // This is an existing topic that you want to attach the subscription with dead letter policy to.
        var topicName = TopicName.FromProjectTopic(projectId, topicId);
        // This is an existing topic that the subscription with dead letter policy forwards dead letter messages to.
        var deadLetterTopic     = TopicName.FromProjectTopic(projectId, deadLetterTopicId).ToString();
        var subscriptionRequest = new Subscription
        {
            SubscriptionName = subscriptionName,
            TopicAsTopicName = topicName,
            DeadLetterPolicy = new DeadLetterPolicy
            {
                DeadLetterTopic = deadLetterTopic,
                // The maximum number of times that the service attempts to deliver a
                // message before forwarding it to the dead letter topic. Must be [5-100].
                MaxDeliveryAttempts = 10
            },
            AckDeadlineSeconds = 30
        };

        var subscription = subscriber.CreateSubscription(subscriptionRequest);

        Console.WriteLine("Created subscription: " + subscription.SubscriptionName.SubscriptionId);
        Console.WriteLine($"It will forward dead letter messages to: {subscription.DeadLetterPolicy.DeadLetterTopic}");
        Console.WriteLine($"After {subscription.DeadLetterPolicy.MaxDeliveryAttempts} delivery attempts.");
        // Remember to attach a subscription to the dead letter topic because
        // messages published to a topic with no subscriptions are lost.
        return(subscription);
    }
示例#2
0
    public Subscription CreateSubscriptionWithOrdering(string projectId, string subscriptionId, string topicId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        var topicName        = TopicName.FromProjectTopic(projectId, topicId);
        var subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        var subscriptionRequest = new Subscription
        {
            SubscriptionName      = subscriptionName,
            TopicAsTopicName      = topicName,
            EnableMessageOrdering = true
        };

        Subscription subscription = null;

        try
        {
            subscription = subscriber.CreateSubscription(subscriptionRequest);
        }
        catch (RpcException e) when(e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            // Already exists.  That's fine.
        }
        return(subscription);
    }
示例#3
0
        public async Task <object> CreateSubscriber(TopicName topic)
        {
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(_projectId, "SubscriptionJ");

            var subscriptionCreated = subscriber.CreateSubscription(subscriptionName, topic, pushConfig: null, ackDeadlineSeconds: 60);

            SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(subscriptionName);

            try
            {
                _ = subscriberClient.StartAsync(
                    async(PubsubMessage message, CancellationToken cancel) =>
                {
                    string text = Encoding.UTF8.GetString(message.Data.ToArray());

                    await Console.Out.WriteLineAsync($"Consumer {message.MessageId} => Message:{text}");

                    Console.WriteLine(message);

                    return(await Task.FromResult(SubscriberClient.Reply.Ack));
                });

                await Task.Delay(3000);

                await subscriberClient.StopAsync(CancellationToken.None);
            }
            catch (RpcException exception)
            {
            }

            return(0);
        }
示例#4
0
        private bool GetSubscriber(out SubscriberServiceApiClient APIClientVar, out SubscriptionName SubscriptionNameVar, string GoogleFriendlyTopicName, Action <string> _ErrorMessageAction = null)
        {
            lock (LockableSubscriberTopicListObject(GoogleFriendlyTopicName))
            {
                APIClientVar        = null;
                SubscriptionNameVar = null;

                var TopicInstance = new TopicName(ProjectID, GoogleFriendlyTopicName);

                if (!EnsureTopicExistence(TopicInstance, null, _ErrorMessageAction))
                {
                    return(false);
                }

                try
                {
                    APIClientVar = SubscriberServiceApiClient.Create(SubscribeChannel);
                }
                catch (Exception e)
                {
                    APIClientVar = null;
                    _ErrorMessageAction?.Invoke("BPubSubServiceGC->GetSubscriber: " + e.Message + ", Trace: " + e.StackTrace);
                    return(false);
                }

                string SubscriptionIDBase        = GoogleFriendlyTopicName + "-";
                int    SubscriptionIDIncrementer = 1;
                SubscriptionNameVar = new SubscriptionName(ProjectID, SubscriptionIDBase + SubscriptionIDIncrementer);

                bool bSubscriptionSuccess = false;
                while (!bSubscriptionSuccess)
                {
                    try
                    {
                        APIClientVar.CreateSubscription(SubscriptionNameVar, TopicInstance, null, 600);
                        bSubscriptionSuccess = true;
                    }
                    catch (Exception e)
                    {
                        if (e is RpcException && (e as RpcException).Status.StatusCode == StatusCode.AlreadyExists)
                        {
                            SubscriptionIDIncrementer++;
                            SubscriptionNameVar = new SubscriptionName(ProjectID, SubscriptionIDBase + SubscriptionIDIncrementer);
                        }
                        else
                        {
                            SubscriptionNameVar = null;
                            _ErrorMessageAction?.Invoke("BPubSubServiceGC->GetSubscriber: " + e.Message + ", Trace: " + e.StackTrace);
                            return(false);
                        }
                    }
                }

                SubscriberTopicList.Add(new BTuple <string, SubscriberServiceApiClient, SubscriptionName>(GoogleFriendlyTopicName, APIClientVar, SubscriptionNameVar));

                return(true);
            }
        }
示例#5
0
        public void Overview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: Overview
            // First create a topic.
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName(projectId, topicId);

            publisher.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriber       = SubscriberServiceApiClient.Create();
            SubscriptionName           subscriptionName = new SubscriptionName(projectId, subscriptionId);

            subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

            // Publish a message to the topic.
            PubsubMessage message = new PubsubMessage
            {
                // The data is any arbitrary ByteString. Here, we're using text.
                Data = ByteString.CopyFromUtf8("Hello, Pubsub"),
                // The attributes provide metadata in a string-to-string dictionary.
                Attributes =
                {
                    { "description", "Simple text message" }
                }
            };

            publisher.Publish(topicName, new[] { message });

            // Pull messages from the subscription. We're returning immediately, whether or not there
            // are messages; in other cases you'll want to allow the call to wait until a message arrives.
            PullResponse response = subscriber.Pull(subscriptionName, returnImmediately: true, maxMessages: 10);

            foreach (ReceivedMessage received in response.ReceivedMessages)
            {
                PubsubMessage msg = received.Message;
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
            }

            // Acknowledge that we've received the messages. If we don't do this within 60 seconds (as specified
            // when we created the subscription) we'll receive the messages again when we next pull.
            subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId));

            // Tidy up by deleting the subscription and the topic.
            subscriber.DeleteSubscription(subscriptionName);
            publisher.DeleteTopic(topicName);
            // End sample

            Assert.Equal(1, response.ReceivedMessages.Count);
            Assert.Equal("Hello, Pubsub", response.ReceivedMessages[0].Message.Data.ToStringUtf8());
            Assert.Equal("Simple text message", response.ReceivedMessages[0].Message.Attributes["description"]);
        }
示例#6
0
        public async Task SimpleOverview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: SimpleOverview
            // First create a topic.
            PublisherServiceApiClient publisherService = await PublisherServiceApiClient.CreateAsync();

            TopicName topicName = new TopicName(projectId, topicId);

            publisherService.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriberService = await SubscriberServiceApiClient.CreateAsync();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

            subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

            // Publish a message to the topic using PublisherClient.
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName);

            // PublishAsync() has various overloads. Here we're using the string overload.
            string messageId = await publisher.PublishAsync("Hello, Pubsub");

            // PublisherClient instance should be shutdown after use.
            // The TimeSpan specifies for how long to attempt to publish locally queued messages.
            await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));

            // Pull messages from the subscription using SimpleSubscriber.
            SubscriberClient subscriber = await SubscriberClient.CreateAsync(subscriptionName);

            List <PubsubMessage> receivedMessages = new List <PubsubMessage>();
            // Start the subscriber listening for messages.
            await subscriber.StartAsync((msg, cancellationToken) =>
            {
                receivedMessages.Add(msg);
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
                // Stop this subscriber after one message is received.
                // This is non-blocking, and the returned Task may be awaited.
                subscriber.StopAsync(TimeSpan.FromSeconds(15));
                // Return Reply.Ack to indicate this message has been handled.
                return(Task.FromResult(SubscriberClient.Reply.Ack));
            });

            // Tidy up by deleting the subscription and the topic.
            subscriberService.DeleteSubscription(subscriptionName);
            publisherService.DeleteTopic(topicName);
            // End sample

            Assert.Equal(1, receivedMessages.Count);
            Assert.Equal("Hello, Pubsub", receivedMessages[0].Data.ToStringUtf8());
        }
示例#7
0
        //Creates or gets a Subscription
        private Subscription CreateGetSubscription()
        {
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            //if subscription exist get it else create it and return it.
            try {
                return(client.GetSubscription(sn));
            }
            catch {
                return(client.CreateSubscription(sn, tn, null, 30));
            }
        }
        private Subscription CreateGetSubscription()
        {
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();  //We check if Subscription exists, if no we create it and return it

            try
            {
                return(client.GetSubscription(sn));
            }
            catch
            {
                return(client.CreateSubscription(sn, tn, null, 30));
            }
        }
示例#9
0
        private Subscription CreateGetSubscription()
        {
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();  //We check if Subscription exists, if no we create it and return it

            try
            {
                return(client.GetSubscription(sn));
            }
            catch (Exception ex)
            {
                new LoggingRepository().ErrorLogging(ex);
                return(client.CreateSubscription(sn, tn, null, 30));
            }
        }
示例#10
0
        private void CheckSubscription()
        {
            SubscriptionName subscriptionName = new SubscriptionName(_options.ProjectId, _topicName);

            _subscriberService = SubscriberServiceApiClient.Create();

            try
            {
                Subscription subscription = _subscriberService.CreateSubscription(subscriptionName, _topic, null, _options.ProcessTimeout);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Subscription já existe.
                }
        }
示例#11
0
        public void StreamingPull()
        {
            // First create a topic.
            PublisherServiceApiClient publisherService = PublisherServiceApiClient.CreateAsync().Result;
            TopicName topicName = new TopicName("k8s-brewery", "sdk-example-test-topic");

            try
            {
                publisherService.CreateTopic(topicName);
            }
            catch
            {
            }

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriberService = SubscriberServiceApiClient.CreateAsync().Result;
            SubscriptionName           subscriptionName  = new SubscriptionName("k8s-brewery", "sdk-example-test-subscription");

            try
            {
                subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
            }
            catch
            {
            }

            // Pull messages from the subscription using SubscriberClient.
            SubscriberClient     subscriber       = SubscriberClient.CreateAsync(subscriptionName).Result;
            List <PubsubMessage> receivedMessages = new List <PubsubMessage>();

            // Start the subscriber listening for messages.
            subscriber.StartAsync((msg, cancellationToken) =>
            {
                using (var span = CustomSpan.Create()
                                  .AsGCPubSubReceive(subscriptionName.SubscriptionId, subscriptionName.ProjectId)
                                  .AsChildOf(() => GetDisInfo(msg)))
                {
                    span.WrapAction(() =>
                    {
                        receivedMessages.Add(msg);
                        Console.WriteLine($"[Test] Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                        Console.WriteLine($"[Test] Text: '{msg.Data.ToStringUtf8()}'");
                    }, true);
                    return(Task.FromResult(SubscriberClient.Reply.Ack));
                }
            });
        }
示例#12
0
    public Subscription CreatePushSubscription(string projectId, string topicId, string subscriptionId, string pushEndpoint)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        TopicName        topicName            = TopicName.FromProjectTopic(projectId, topicId);
        SubscriptionName subscriptionName     = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        PushConfig pushConfig = new PushConfig {
            PushEndpoint = pushEndpoint
        };

        // The approximate amount of time in seconds (on a best-effort basis) Pub/Sub waits for the
        // subscriber to acknowledge receipt before resending the message.
        var ackDeadlineSeconds = 60;
        var subscription       = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig, ackDeadlineSeconds);

        return(subscription);
    }
示例#13
0
        private Subscription GetOrCreateSubscription(string name, string topicName)
        {
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            try
            {
                return(client.GetSubscription(new SubscriptionName("programming-for-the-cloud", name)));
            }
            catch (RpcException ex)
            {
                if (ex.Status.StatusCode == StatusCode.NotFound)
                {
                    return(client.CreateSubscription(new SubscriptionName("programming-for-the-cloud", name), GetOrCreateTopic(topicName).TopicName, null, 60));
                }
            }
            return(null);
        }
    public Subscription CreateSubscription(string projectId, string topicId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);

        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        Subscription     subscription     = null;

        try
        {
            subscription = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
        }
        catch (RpcException e) when(e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            // Already exists.  That's fine.
        }
        return(subscription);
    }
示例#15
0
        private void CheckSubscription()
        {
            TopicName        topicName        = new TopicName(_options.ProjectId, _topic);
            SubscriptionName subscriptionName = new SubscriptionName(_options.ProjectId, _subscriptionId);

            try
            {
                Subscription subscription = _subscriberService.CreateSubscription(
                    subscriptionName, topicName, pushConfig: null,
                    ackDeadlineSeconds: _options.ProcessTimeout);

                Console.WriteLine("a");
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Subscription já existe.
                }
        }
示例#16
0
        public static object CreateSubscription(string projectId, string topicId, string subscriptionId)
        {
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            TopicName        topicName            = new TopicName(projectId, topicId);
            SubscriptionName subscriptionName     = new SubscriptionName(projectId, subscriptionId);

            try
            {
                Subscription subscription = subscriber.CreateSubscription(
                    subscriptionName, topicName, pushConfig: null,
                    ackDeadlineSeconds: 60);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                }

            return(0);
        }
示例#17
0
        public void CreateSubscription()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherServiceApiClient.Create().CreateTopic(new TopicName(projectId, topicId));

            // Snippet: CreateSubscription(SubscriptionName,*,*,*,*)
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
            TopicName        topicName        = new TopicName(projectId, topicId);
            Subscription     subscription     = client.CreateSubscription(
                subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 30);

            Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}");
            // End snippet
        }
示例#18
0
        public object CreateSubscription([FromBody] CreatTopicModel attr)
        {
            // [START pubsub_create_pull_subscription]
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            TopicName        topicName            = new TopicName(attr.projectId, attr.topicId);
            SubscriptionName subscriptionName     = new SubscriptionName(attr.projectId, attr.subscriptionID);

            try
            {
                Subscription subscription = subscriber.CreateSubscription(
                    subscriptionName, topicName, pushConfig: null,
                    ackDeadlineSeconds: 60);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
            // [END pubsub_create_pull_subscription]
            return(0);
        }
示例#19
0
        /// <summary>
        /// Creates a topic subscription if doesnt exist
        /// </summary>
        /// <returns>Subscription name</returns>
        private SubscriptionName CreateSubscriptionIfNotExists()
        {
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            TopicName        topicName            = new TopicName(this.cloud.GoogleProjectID, this.cloud.QueueName);
            SubscriptionName subscriptionName     = new SubscriptionName(this.cloud.GoogleProjectID, this.cloud.GoogleSubscriptionName);

            try
            {
                _ = subscriber.CreateSubscription(
                    subscriptionName,
                    topicName,
                    pushConfig: null,
                    ackDeadlineSeconds: 60);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // It already exists
                }

            return(subscriptionName);
        }
示例#20
0
        // [START retry]
        internal void RpcRetry(string topicId, string subscriptionId,
                               PublisherServiceApiClient publisher, SubscriberServiceApiClient subscriber)
        {
            TopicName topicName = new TopicName(_projectId, topicId);
            // Create Subscription.
            SubscriptionName subscriptionName = new SubscriptionName(_projectId,
                                                                     subscriptionId);

            // Create Topic
            try
            {
                // This may fail if the Topic already exists.
                // Don't retry in that case.
                publisher.CreateTopic(topicName, newRetryCallSettings(3,
                                                                      StatusCode.AlreadyExists));
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
            try
            {
                // Subscribe to Topic
                // This may fail if the Subscription already exists or
                // the Topic has not yet been created.  In those cases, don't
                // retry, because a retry would fail the same way.
                subscriber.CreateSubscription(subscriptionName, topicName,
                                              pushConfig: null, ackDeadlineSeconds: 60,
                                              callSettings: newRetryCallSettings(3, StatusCode.AlreadyExists,
                                                                                 StatusCode.NotFound));
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
        }
        static void Main(string[] args)
        {
            GCPublisherService  gcPublisherService  = new GCPublisherService();
            GCSubscriberService gcSubscriberService = new GCSubscriberService();

            gcPublisherService.StartPeriodicallyPublish(2000);
            gcSubscriberService.StreamingPull();

            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName("k8s-brewery", "sdk-example-test-topic-2");

            try
            {
                publisher.CreateTopic(topicName);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to create topic");
            }

            // Publish a message to the topic.
            PubsubMessage message = new PubsubMessage
            {
                Data       = ByteString.CopyFromUtf8("Message "),
                Attributes =
                {
                    { "Description", "Simple text message " }
                }
            };

            publisher.Publish(topicName, new[] { message });

            SubscriberServiceApiClient subscriber       = SubscriberServiceApiClient.Create();
            SubscriptionName           subscriptionName = new SubscriptionName("k8s-brewery", "sdk-example-test-subscription-2");

            try
            {
                subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to create subscription");
            }

            PullResponse response = subscriber.Pull(subscriptionName, returnImmediately: true, maxMessages: 100);

            foreach (ReceivedMessage received in response.ReceivedMessages)
            {
                using (var span = CustomSpan.Create()
                                  .AsGCPubSubReceive(subscriptionName.SubscriptionId, subscriptionName.ProjectId)
                                  .AsChildOf(() => GCSubscriberService.GetDisInfo(received.Message)))
                {
                    span.WrapAction(() =>
                    {
                        PubsubMessage msg = received.Message;
                        Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                        Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
                        Console.WriteLine($"Attributes: '{string.Join(",", msg.Attributes.Select(x => $"{x.Key}-{x.Value}"))}'");
                    }, true);
                }
            }
            if (response.ReceivedMessages.Count > 0)
            {
                subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId));
            }

            Console.WriteLine("Press any key to close ...");
            Console.ReadKey();
        }
    public async Task WithEmulatorAsync(string projectId, string topicId, string subscriptionId)
    {
        // Use EmulatorDetection.EmulatorOrProduction to create service clients that will
        // that will connect to the PubSub emulator if the PUBSUB_EMULATOR_HOST environment
        // variable is set, but will otherwise connect to the production environment.

        // Create the PublisherServiceApiClient using the PublisherServiceApiClientBuilder
        // and setting the EmulatorDection property.
        PublisherServiceApiClient publisherService = await new PublisherServiceApiClientBuilder
        {
            EmulatorDetection = EmulatorDetection.EmulatorOrProduction
        }.BuildAsync();

        // Use the client as you'd normally do, to create a topic in this example.
        TopicName topicName = new TopicName(projectId, topicId);

        publisherService.CreateTopic(topicName);

        // Create the SubscriberServiceApiClient using the SubscriberServiceApiClientBuilder
        // and setting the EmulatorDection property.
        SubscriberServiceApiClient subscriberService = await new SubscriberServiceApiClientBuilder
        {
            EmulatorDetection = EmulatorDetection.EmulatorOrProduction
        }.BuildAsync();

        // Use the client as you'd normally do, to create a subscription in this example.
        SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

        subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

        // Create the PublisherClient using PublisherClient.ClientCreationSettings
        // and call the WithEmulatorDection method.
        PublisherClient publisher = await PublisherClient.CreateAsync(
            topicName,
            new PublisherClient.ClientCreationSettings()
            .WithEmulatorDetection(EmulatorDetection.EmulatorOrProduction));

        // Use the client as you'd normally do, to send a message in this example.
        await publisher.PublishAsync("Hello, Pubsub");

        await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));

        // Create the SubscriberClient using SubscriberClient.ClientCreationSettings
        // and call the WithEmulatorDection method.
        SubscriberClient subscriber = await SubscriberClient.CreateAsync(
            subscriptionName,
            new SubscriberClient.ClientCreationSettings()
            .WithEmulatorDetection(EmulatorDetection.EmulatorOrProduction));

        List <PubsubMessage> receivedMessages = new List <PubsubMessage>();

        // Use the client as you'd normally do, to listen for messages in this example.
        await subscriber.StartAsync((msg, cancellationToken) =>
        {
            receivedMessages.Add(msg);
            Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
            Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
            // In this example we stop the subscriber when the message is received.
            // You may leave the subscriber running, and it will continue to received published messages
            // if any.
            // This is non-blocking, and the returned Task may be awaited.
            subscriber.StopAsync(TimeSpan.FromSeconds(15));
            // Return Reply.Ack to indicate this message has been handled.
            return(Task.FromResult(SubscriberClient.Reply.Ack));
        });
    }
示例#23
0
        private static void Start()
        {
            SubscriberClient _subscriber;
            PublisherClient  _publisher;
            // Instantiates a client
            PublisherServiceApiClient publisherApi = PublisherServiceApiClient.Create();
            // Subscribe to the topic.
            TopicName                  pubsubTopicName  = new TopicName(projectId, topicName);
            SubscriptionName           subscriptionName = new SubscriptionName(projectId, subscriptionId);
            SubscriberServiceApiClient subscriberApi    = SubscriberServiceApiClient.Create();

            // Creates the new topic
            try
            {
                Topic topic = publisherApi.CreateTopic(pubsubTopicName);
                Console.WriteLine($"Topic {topic.Name} created.");
            }
            catch (Grpc.Core.RpcException e)
                when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
                {
                    Console.WriteLine($"Topic {topicName} already exists.");
                }
            // Create the new subscription
            try
            {
                subscriberApi.CreateSubscription(subscriptionName, pubsubTopicName, null, 120);
                Console.WriteLine($"Subscription {subscriptionName.Kind} created.");
            }
            catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
            {
                // OK
                Console.WriteLine($"Subscription {subscriptionName.Kind} already exists");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            _subscriber = SubscriberClient.Create(subscriptionName, new[] { subscriberApi });

            _publisher = PublisherClient.Create(pubsubTopicName, new[] { publisherApi });

            _publisher.PublishAsync("Bla-Bla-Bla-Message.");

            _subscriber.StartAsync((message, token) =>
            {
                string data = message.Data.ToStringUtf8();
                try
                {
                    Console.WriteLine($"Pubsub message id={message.MessageId}, " +
                                      $"created at {message.PublishTime}, data{message.Data.ToStringUtf8()}");

                    // TODO: Replace with ACK
                    return(System.Threading.Tasks.Task.FromResult(SubscriberClient.Reply.Nack));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return(System.Threading.Tasks.Task.FromResult(SubscriberClient.Reply.Nack));
                }
            });

            // VARIAN II :

            // Pull messages from the subscription.We're returning immediately, whether or not there
            // are messages; in other cases you'll want to allow the call to wait until a message arrives.
            PullResponse response = subscriberApi.Pull(subscriptionName, returnImmediately: true, maxMessages: 10);

            foreach (ReceivedMessage received in response.ReceivedMessages)
            {
                PubsubMessage msg = received.Message;
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
            }
            // Acknowledge that we've received the messages. If we don't do this within 60 seconds (as specified
            // when we created the subscription) we'll receive the messages again when we next pull.
            subscriberApi.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId));

            // Tidy up by deleting the subscription and the topic.
            subscriberApi.DeleteSubscription(subscriptionName);
            publisherApi.DeleteTopic(pubsubTopicName);
        }
示例#24
0
        public async Task StreamingPull()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Snippet: StreamingPull(*, *)
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName(projectId, topicId);

            publisher.CreateTopic(topicName);
            SubscriberServiceApiClient subscriber       = SubscriberServiceApiClient.Create();
            SubscriptionName           subscriptionName = new SubscriptionName(projectId, subscriptionId);

            subscriber.CreateSubscription(subscriptionName, topicName, null, 60);

            // If we don't see all the messages we expect in 10 seconds, we'll cancel the call.
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            CallSettings            callSettings            = CallSettings.FromCancellationToken(cancellationTokenSource.Token);

            SubscriberServiceApiClient.StreamingPullStream stream = subscriber.StreamingPull(callSettings);

            // The first request must include the subscription name and the stream ack deadline
            await stream.WriteAsync(new StreamingPullRequest { SubscriptionAsSubscriptionName = subscriptionName, StreamAckDeadlineSeconds = 20 });

            Task pullingTask = Task.Run(async() =>
            {
                int messagesSeen = 0;
                IAsyncEnumerator <StreamingPullResponse> responseStream = stream.ResponseStream;

                // Handle responses as we see them.
                while (await responseStream.MoveNext())
                {
                    StreamingPullResponse response = responseStream.Current;
                    Console.WriteLine("Received streaming response");
                    foreach (ReceivedMessage message in response.ReceivedMessages)
                    {
                        // Messages can contain any data. We'll assume that we know this
                        // topic publishes UTF-8-encoded text.
                        Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
                    }
                    // Acknowledge the messages we've just seen
                    await stream.WriteAsync(new StreamingPullRequest {
                        AckIds = { response.ReceivedMessages.Select(rm => rm.AckId) }
                    });

                    // If we've seen all the messages we expect, we can complete the streaming call,
                    // and our next MoveNext call will return false.
                    messagesSeen += response.ReceivedMessages.Count;
                    if (messagesSeen == 3)
                    {
                        await stream.WriteCompleteAsync();
                    }
                }
            });

            publisher.Publish(topicName, new[] { new PubsubMessage {
                                                     Data = ByteString.CopyFromUtf8("Message 1")
                                                 } });
            publisher.Publish(topicName, new[] { new PubsubMessage {
                                                     Data = ByteString.CopyFromUtf8("Message 2")
                                                 } });
            publisher.Publish(topicName, new[] { new PubsubMessage {
                                                     Data = ByteString.CopyFromUtf8("Message 3")
                                                 } });

            await pullingTask;
            // End snippet
        }