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(); string topicName = PublisherClient.FormatTopicName(projectId, topicId); publisher.CreateTopic(topicName); // Subscribe to the topic. SubscriberClient subscriber = SubscriberClient.Create(); string subscriptionName = SubscriberClient.FormatSubscriptionName(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 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 }