/// <summary>
 /// Creates the topic and subscription, if they don't already exist.  You should call this
 /// once at the beginning of your app.
 /// </summary>
 // [START createtopicandsubscription]
 public void CreateTopicAndSubscription()
 {
     try
     {
         _pub.CreateTopic(_topicName);
         _logger.LogVerbose("Created topic " + _topicName);
     }
     catch (Grpc.Core.RpcException e)
         when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
         {
             // The topic already exists.  Ok.
             _logger.LogError(_topicName + " already exists", e);
         }
     try
     {
         _sub.CreateSubscription(_subscriptionName, _topicName, null, 0);
         _logger.LogVerbose("Created subscription " + _subscriptionName);
     }
     catch (Grpc.Core.RpcException e)
         when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
         {
             // The subscription already exists.  Ok.
             _logger.LogError(_subscriptionName + " already exists", e);
         }
 }
        public void CallSettings_Client()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Sample: CallSettings_ClientWide
            // Create a default PublisherSettings, with a custom header for calls to all RPC methods.
            PublisherSettings publisherSettings = new PublisherSettings
            {
                CallSettings = new CallSettings
                {
                    Headers = new Metadata
                    {
                        { "ClientVersion", "1.0.0" }
                    },
                }
            };
            PublisherClient client = PublisherClient.Create(settings: publisherSettings);
            // Format topicName from the projectId and topicId.
            string topicName = PublisherClient.FormatTopicName(projectId, topicId);
            // The custom 'ClientVersion' header will be included in the RPC call, due to
            // the client being configured with 'publishersettings' above.
            Topic topic = client.CreateTopic(topicName);
            // End sample
        }
        public void Publish()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Snippet: Publish
            PublisherClient client = PublisherClient.Create();
            // Make sure we have a topic to publish to
            string topicName = PublisherClient.FormatTopicName(projectId, topicId);

            client.CreateTopic(topicName);

            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" }
                }
            };

            client.Publish(topicName, new[] { message });
            // End snippet
        }
 /// <summary>
 /// Create a topic and subscription once.
 /// </summary>
 /// <param name="provider"></param>
 void CreateTopicAndSubscriptionOnce(PublisherClient publisher,
     TopicName topicName)
 {
     if (s_topicAndSubscriptionExist)
         return;
     try
     {
         publisher.CreateTopic(topicName);
     }
     catch (Grpc.Core.RpcException e)
     when (e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
     {
     }
     var subscriptionName = new SubscriptionName(
             _options.ProjectId, _options.SubscriptionId);
     var pushConfig = new PushConfig()
     {
         PushEndpoint = $"https://{_options.ProjectId}.appspot.com/Push"
     };
     try
     {
         _subscriber.CreateSubscription(subscriptionName, topicName,
             pushConfig, 20);
     }
     catch (Grpc.Core.RpcException e)
     when (e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
     {
         _subscriber.ModifyPushConfig(subscriptionName, pushConfig);
     }
     s_topicAndSubscriptionExist = true;
 }
示例#5
0
        public static void Main(string[] args)
        {
            // Instantiates a client
            PublisherClient publisher = PublisherClient.Create();

            // Your Google Cloud Platform project ID
            string projectId = "YOUR-PROJECT-ID";

            // [END pubsub_quickstart]
            Debug.Assert(projectId != "YOUR-PROJECT" + "-ID",
                         "Edit Program.cs and replace YOUR-PROJECT-ID with your project id.");
            // [START pubsub_quickstart]

            // The name for the new topic
            var topicName = new TopicName(projectId, "my-new-topic");

            // Creates the new topic
            try
            {
                Topic topic = publisher.CreateTopic(topicName);
                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.");
                }
        }
示例#6
0
        //Create Topic per Rule
        public TopicName CreatePubSubTopic(String topicId)
        {
            TopicName topicName = new TopicName(ProjectId, topicId);

            PublisherClient.CreateTopic(topicName);
            return(topicName);
        }
示例#7
0
        public void CreateTopic(string topicId, PublisherClient publisher)
        {
            // [START create_topic]
            string topicName = PublisherClient.FormatTopicName(_projectId,
                                                               topicId);

            publisher.CreateTopic(topicName);
            // [END create_topic]
        }
示例#8
0
        public void Overview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

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

            publisher.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberClient subscriber       = SubscriberClient.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"]);
        }
        public async Task SimpleOverview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: SimpleOverview
            // First create a topic.
            PublisherClient publisher = await PublisherClient.CreateAsync();

            TopicName topicName = new TopicName(projectId, topicId);

            publisher.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberClient subscriber = await SubscriberClient.CreateAsync();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

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

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

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

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

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

            List <PubsubMessage> receivedMessages = new List <PubsubMessage>();
            // Start the subscriber listening for messages.
            await simpleSubscriber.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.
                simpleSubscriber.StopAsync(TimeSpan.FromSeconds(15));
                // Return Reply.Ack to indicate this message has been handled.
                return(Task.FromResult(SimpleSubscriber.Reply.Ack));
            });

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

            Assert.Equal(1, receivedMessages.Count);
            Assert.Equal("Hello, Pubsub", receivedMessages[0].Data.ToStringUtf8());
        }
示例#10
0
        // [START retry]
        public void RpcRetry(string topicId, string subscriptionId,
                             PublisherClient publisher, SubscriberClient subscriber)
        {
            string topicName        = PublisherClient.FormatTopicName(_projectId, topicId);
            string subscriptionName =
                SubscriberClient.FormatSubscriptionName(_projectId, subscriptionId);
            var delayMs = _retryDelayMs;

            for (int tries = 1; true; ++tries)
            {
                try
                {
                    // Subscribe to Topic
                    // This may fail if the Subscription already exists or
                    // the Topic has not yet been created.
                    subscriber.CreateSubscription(subscriptionName, topicName,
                                                  pushConfig: null, ackDeadlineSeconds: 60);
                    break;
                }
                catch (RpcException e) when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    break;
                }
                catch (RpcException) when(tries < _retryCount)
                {
                    System.Threading.Thread.Sleep(delayMs);
                    delayMs *= 2;  // Exponential back-off.
                }
                catch (RpcException) when(tries == _retryCount)
                {
                    //Number of retries set in _retryCount has been reached
                    break;
                }
            }

            // Create Topic
            delayMs = _retryDelayMs;
            for (int tries = 1; true; ++tries)
            {
                try
                {
                    publisher.CreateTopic(topicName);
                    break;
                }
                catch (RpcException e) when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    break;
                }
                catch (RpcException) when(tries < 3)
                {
                    System.Threading.Thread.Sleep(delayMs);
                    delayMs *= 2;  // Exponential back-off.
                }
            }
        }
 public void CreateTopic()
 {
     // Snippet: CreateTopic(string,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     string formattedName = PublisherClient.FormatTopicName("[PROJECT]", "[TOPIC]");
     // Make the request
     Topic response = publisherClient.CreateTopic(formattedName);
     // End snippet
 }
 public void CreateTopic()
 {
     // Snippet: CreateTopic(TopicName,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     TopicName name = new TopicName("[PROJECT]", "[TOPIC]");
     // Make the request
     Topic response = publisherClient.CreateTopic(name);
     // End snippet
 }
    public void CreateTopic()
    {
        // <CreateTopic>
        PublisherClient client = PublisherClient.Create();

        // Alternative: use a known topic resource name
        // projects/{PROJECT_ID}/topics/{TOPIC_ID}
        string topicName = PublisherClient.GetTopicName("{PROJECT_ID}", "{TOPIC_ID}");
        Topic  topic     = client.CreateTopic(topicName);

        Console.WriteLine($"Created {topic.Name}");
        // </CreateTopic>
    }
示例#14
0
        public void CreateTopic()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Snippet: CreateTopic(TopicName,*)
            PublisherClient client = PublisherClient.Create();

            TopicName topicName = new TopicName(projectId, topicId);
            Topic     topic     = client.CreateTopic(topicName);

            Console.WriteLine($"Created {topic.Name}");
            // End snippet
        }
示例#15
0
        public void CreateTopic(string topicId, PublisherClient publisher)
        {
            // [START create_topic]
            TopicName topicName = new TopicName(_projectId, topicId);

            try
            {
                publisher.CreateTopic(topicName);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
            // [END create_topic]
        }
示例#16
0
        public void Emulator()
        {
            // Sample: Emulator
            // For example, "localhost:8615"
            string emulatorHostAndPort = Environment.GetEnvironmentVariable("PUBSUB_EMULATOR_HOST");

            Channel         channel = new Channel(emulatorHostAndPort, ChannelCredentials.Insecure);
            PublisherClient client  = PublisherClient.Create(channel);

            client.CreateTopic(new TopicName("project", "topic"));
            foreach (var topic in client.ListTopics(new ProjectName("project")))
            {
                Console.WriteLine(topic.Name);
            }
            // End sample
        }
        public void CreateTopic()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Snippet: CreateTopic
            PublisherClient client = PublisherClient.Create();

            // Alternative: use a known topic resource name
            // "projects/{PROJECT_ID}/topics/{TOPIC_ID}"
            string topicName = PublisherClient.FormatTopicName(projectId, topicId);
            Topic  topic     = client.CreateTopic(topicName);

            Console.WriteLine($"Created {topic.Name}");
            // End snippet
        }
示例#18
0
        public void PerRpc()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Sample: PerRpc
            // Create a PublisherClient with default settings.
            PublisherClient client = PublisherClient.Create();
            // Create a topic name from the projectId and topicId.
            TopicName topicName = new TopicName(projectId, topicId);
            // Create a CallSettings with a custom header.
            CallSettings callSettings = new CallSettings(null, null, null, metadata => metadata.Add("ClientVersion", "1.0.0"), null, null);
            // This will cause the custom 'ClientVersion' header to be included in the RPC call.
            Topic topic = client.CreateTopic(topicName, callSettings);
            // End sample
        }
        public void CallSettings_Overrides()
        {
            string            projectId         = _fixture.ProjectId;
            string            topicId           = _fixture.CreateTopicId();
            DateTime          deadline          = DateTime.MaxValue;
            CancellationToken cancellationToken = new CancellationTokenSource().Token;

            // Sample: CallSettings_Overrides
            // Create a default PublisherSettings, with customizations for CreateTopic RPCs:
            // * A custom "ClientVersion" header.
            // * A custom 5-second timeout Timing.
            // * No cancellation token.
            PublisherSettings publisherSettings = new PublisherSettings();

            publisherSettings.CreateTopicSettings.Headers = new Metadata
            {
                { "ClientVersion", "1.0.0" }
            };
            publisherSettings.CreateTopicSettings.Timing            = CallTiming.FromTimeout(TimeSpan.FromSeconds(5));
            publisherSettings.CreateTopicSettings.CancellationToken = CancellationToken.None;

            // Override the above Timing and CancellationToken in the client-wide CallSettings;
            // the Headers are not overridden.
            publisherSettings.CallSettings = new CallSettings
            {
                Timing            = CallTiming.FromDeadline(deadline),
                CancellationToken = CancellationToken.None,
            };

            // Create the client with the configured publisherSettings
            PublisherClient client = PublisherClient.Create(settings: publisherSettings);

            // Format topicName from the projectId and topicId.
            string topicName = PublisherClient.FormatTopicName(projectId, topicId);

            // Call CreateTopic(). Override only the CancellationToken, using a per-RPC-method CallSettings.
            // The CallSettings used during this RPC invocation is:
            // * A custom "ClientVersion" header.
            // * A Timing deadline of 'deadline' (*not* the overridden 5-second timeout).
            // * The CancellationToken 'cancellationToken' (*not* CancellationToken.None).
            Topic topic = client.CreateTopic(topicName, new CallSettings
            {
                CancellationToken = cancellationToken
            });
            // End sample
        }
示例#20
0
        public void NotificationsOverview()
        {
            string projectId = _fixture.ProjectId;
            string bucket    = _fixture.BucketName;
            string topicId   = "topic-" + Guid.NewGuid().ToString().ToLowerInvariant();

            // Sample: NotificationsOverview
            // First create a Pub/Sub topic.
            PublisherClient publisherClient = PublisherClient.Create();
            TopicName       topicName       = new TopicName(projectId, topicId);

            publisherClient.CreateTopic(topicName);

            // Prepare the topic for Storage notifications. The Storage Service Account must have Publish permission
            // for the topic. The code below adds the service account into the "roles/pubsub.publisher" role for the topic.

            // Determine the Storage Service Account name to use in IAM operations.
            StorageClient storageClient         = StorageClient.Create();
            string        storageServiceAccount = $"serviceAccount:{storageClient.GetStorageServiceAccountEmail(projectId)}";

            // Fetch the IAM policy for the topic.
            Iam.V1.Policy policy = publisherClient.GetIamPolicy(topicName.ToString());
            var           role   = "roles/pubsub.publisher";

            // Ensure the Storage Service Account is in the publisher role, setting the IAM policy for the topic
            // on the server if necessary.
            if (policy.AddRoleMember(role, storageServiceAccount))
            {
                publisherClient.SetIamPolicy(topicName.ToString(), policy);
            }

            // Now that the topic is ready, we can create a notification configuration for Storage
            Notification notification = new Notification
            {
                Topic         = $"//pubsub.googleapis.com/{topicName}",
                PayloadFormat = "JSON_API_V1"
            };

            notification = storageClient.CreateNotification(bucket, notification);
            Console.WriteLine($"Created notification ID: {notification.Id}");

            // End sample

            _fixture.RegisterTopicToDelete(topicName);
        }
示例#21
0
        public void ClientPerMethod()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Sample: ClientPerMethod
            // Create a default PublisherSettings, with a custom header for calls
            // to the CreateTopic RPC method.
            PublisherSettings publisherSettings = new PublisherSettings();

            publisherSettings.CreateTopicSettings = publisherSettings.CreateTopicSettings.WithHeader("ClientVersion", "1.0.0");
            PublisherClient client = PublisherClient.Create(settings: publisherSettings);
            // Create a topic name from the projectId and topicId.
            TopicName topicName = new TopicName(projectId, topicId);
            // The custom 'ClientVersion' header will be included in the RPC call, due to
            // the client being configured with 'publishersettings' above.
            Topic topic = client.CreateTopic(topicName);
            // End sample
        }
        public async Task PullAsync()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherClient publisher = PublisherClient.Create();
            string          topicName = PublisherClient.FormatTopicName(projectId, topicId);

            publisher.CreateTopic(topicName);
            PubsubMessage newMessage = new PubsubMessage {
                Data = ByteString.CopyFromUtf8("Simple text")
            };

            SubscriberClient.Create().CreateSubscription(SubscriberClient.FormatSubscriptionName(projectId, subscriptionId), topicName, null, 60);
            publisher.Publish(topicName, new[] { newMessage });

            // Snippet: PullAsync(string,*,*,CallSettings)
            // Additional: PullAsync(string,*,*,CancellationToken)
            SubscriberClient client = SubscriberClient.Create();

            // Alternative: use an existing subscription resource name:
            // "projects/{PROJECT_ID}/subscriptions/{SUBSCRIPTION_ID}"
            string subscriptionName = SubscriberClient.FormatSubscriptionName(projectId, subscriptionId);

            PullResponse pullResponse = await client.PullAsync(subscriptionName, returnImmediately : false, maxMessages : 100);

            foreach (ReceivedMessage message in pullResponse.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 after pulling them, so we don't pull them
            // a second time later. The ackDeadlineSeconds parameter specified when
            // the subscription is created determines how quickly you need to acknowledge
            // successfully-pulled messages before they will be redelivered.
            var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);
            await client.AcknowledgeAsync(subscriptionName, ackIds);

            // End snippet
        }
示例#23
0
        public static void Main_HelloWorldPubSub()
        {
            // Instantiates a client
            PublisherClient publisher = PublisherClient.Create();

            // Your Google Cloud Platform project ID
            string projectId = "pushnotificationpoc-19baf";

            // The name for the new topic
            string topicName = "my-new-topic";

            // The fully qualified name for the new topic
            string formattedTopicName = PublisherClient.FormatTopicName(projectId, topicName);

            // Creates the new topic
            Topic topic = publisher.CreateTopic(formattedTopicName);

            Console.WriteLine($"Topic {topic.Name} created.");
        }
示例#24
0
        public static object CreateTopic(string projectId, string topicId)
        {
            // [START create_publisher_client]
            PublisherClient publisher = PublisherClient.Create();
            // [END create_publisher_client]

            // [START create_topic]
            TopicName topicName = new TopicName(projectId, topicId);

            try
            {
                publisher.CreateTopic(topicName);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
            // [END create_topic]
            return(0);
        }
示例#25
0
        public void Pull()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherClient publisher = PublisherClient.Create();
            TopicName       topicName = new TopicName(projectId, topicId);

            publisher.CreateTopic(topicName);
            PubsubMessage newMessage = new PubsubMessage {
                Data = ByteString.CopyFromUtf8("Simple text")
            };

            SubscriberClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60);
            publisher.Publish(topicName, new[] { newMessage });

            // Snippet: Pull(*,*,*,*)
            SubscriberClient client = SubscriberClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

            PullResponse pullResponse = client.Pull(subscriptionName, returnImmediately: false, maxMessages: 100);

            foreach (ReceivedMessage message in pullResponse.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 after pulling them, so we don't pull them
            // a second time later. The ackDeadlineSeconds parameter specified when
            // the subscription is created determines how quickly you need to acknowledge
            // successfully-pulled messages before they will be redelivered.
            var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);

            client.Acknowledge(subscriptionName, ackIds);
            // End snippet
        }
        public void CallSettings_PerRpc()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Sample: CallSettings_PerRpc
            // Create a PublisherClient with default settings.
            PublisherClient client = PublisherClient.Create();
            // Format topicName from the projectId and topicId.
            string topicName = PublisherClient.FormatTopicName(projectId, topicId);
            // Create a CallSettings with a custom header.
            CallSettings callSettings = new CallSettings
            {
                Headers = new Metadata
                {
                    { "ClientVersion", "1.0.0" }
                }
            };
            // This will cause the custom 'ClientVersion' header to be included in the RPC call.
            Topic topic = client.CreateTopic(topicName, callSettings);
            // End sample
        }
示例#27
0
        // [START retry]
        public void RpcRetry(string topicId, string subscriptionId,
                             PublisherClient publisher, SubscriberClient subscriber)
        {
            string topicName = PublisherClient.FormatTopicName(_projectId,
                                                               topicId);
            string subscriptionName =
                // Create Subscription.
                SubscriberClient.FormatSubscriptionName(_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.
                }
        }
 public void CreateTopic(string topicId, PublisherClient publisher)
 {
     // [START create_topic]
     string topicName = PublisherClient.FormatTopicName(_projectId,
         topicId);
     try
     {
         publisher.CreateTopic(topicName);
     }
     catch (RpcException e)
     when (e.Status.StatusCode == StatusCode.AlreadyExists)
     {
         // Already exists.  That's fine.
     }
     // [END create_topic]
 }
示例#29
0
        public async Task StreamingPull()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

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

            publisher.CreateTopic(topicName);
            SubscriberClient subscriber       = SubscriberClient.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);

            SubscriberClient.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
        }
 // [START retry]
 public void RpcRetry(string topicId, string subscriptionId,
     PublisherClient publisher, SubscriberClient subscriber)
 {
     string topicName = PublisherClient.FormatTopicName(_projectId,
         topicId);
     string subscriptionName =
     // Create Subscription.
     SubscriberClient.FormatSubscriptionName(_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.
     }
 }