public void PublishMessage(string message, string topicName) { PublisherServiceApiClient client = PublisherServiceApiClient.Create(); Topic MyTopic = GetOrCreateTopic(topicName); List <PubsubMessage> myMessages = new List <PubsubMessage>(); myMessages.Add(new PubsubMessage() { //create mailmessage object instead of string //serialize mailmessage and convert to binary by using binary formatter //and pass to the below: ByteString.CopyFrom <- array of bytes or use ByteString.FromStream MessageId = Guid.NewGuid().ToString(), PublishTime = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.UtcNow), Data = ByteString.CopyFromUtf8(message) }); try { client.Publish(MyTopic.TopicName, myMessages); } catch (Exception ex) { } }
public void StartPeriodicallyPublish(int timeIntervalInSeconds) { PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName("k8s-brewery", "sdk-example-test-topic"); try { publisher.CreateTopic(topicName); } catch (Exception) { Console.WriteLine("Failed to create topic"); } int j = 0; Task.Run(() => { while (!token.IsCancellationRequested) { // Publish a message to the topic. PubsubMessage message = new PubsubMessage { Data = ByteString.CopyFromUtf8("Test message number " + j), Attributes = { { "description", "Simple text message number " + j } } }; publisher.Publish(topicName, new[] { message }); j++; Thread.Sleep(timeIntervalInSeconds * 1000); } }); }
public Topic CreateTopic(string projectId, string topicId) { PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); var topicName = TopicName.FromProjectTopic(projectId, topicId); Topic topic = null; try { topic = publisher.CreateTopic(topicName); Console.WriteLine($"Topic {topic.Name} created."); } catch (RpcException e) when(e.Status.StatusCode == StatusCode.AlreadyExists) { Console.WriteLine($"Topic {topicName} already exists."); } 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 }); return(topic); }
public void Publish() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); // Snippet: Publish(*,*,*) PublisherServiceApiClient client = PublisherServiceApiClient.Create(); // Make sure we have a topic to publish to TopicName topicName = new TopicName(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 }
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"]); }
/// <summary>Snippet for Publish</summary> public void PublishResourceNames() { // Snippet: Publish(TopicName, IEnumerable<PubsubMessage>, CallSettings) // Create client PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create(); // Initialize request argument(s) TopicName topic = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"); IEnumerable <PubsubMessage> messages = new PubsubMessage[] { new PubsubMessage(), }; // Make the request PublishResponse response = publisherServiceApiClient.Publish(topic, messages); // End snippet }
/// <summary>Snippet for Publish</summary> public void Publish() { // Snippet: Publish(string, IEnumerable<PubsubMessage>, CallSettings) // Create client PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create(); // Initialize request argument(s) string topic = "projects/[PROJECT]/topics/[TOPIC]"; IEnumerable <PubsubMessage> messages = new PubsubMessage[] { new PubsubMessage(), }; // Make the request PublishResponse response = publisherServiceApiClient.Publish(topic, messages); // End snippet }
public void PublishMessage(string projectId, string topicId) { PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); var topicName = TopicName.FromProjectTopic(projectId, topicId); 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 }); }
/// <summary>Snippet for Publish</summary> public void PublishRequestObject() { // Snippet: Publish(PublishRequest, CallSettings) // Create client PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create(); // Initialize request argument(s) PublishRequest request = new PublishRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage(), }, }; // Make the request PublishResponse response = publisherServiceApiClient.Publish(request); // End snippet }
/// <summary> /// Publish method: uploads a message to the queue /// </summary> /// <param name="p"></param> public void AddToEmailQueue(Product p) { PublisherServiceApiClient client = PublisherServiceApiClient.Create(); var t = CreateGetTopic(); string serialized = JsonSerializer.Serialize(p, typeof(Product)); List <PubsubMessage> messagesToAddToQueue = new List <PubsubMessage>(); // the method takes a list, so you can upload more than 1 message/item/product at a time PubsubMessage msg = new PubsubMessage(); msg.Data = ByteString.CopyFromUtf8(serialized); messagesToAddToQueue.Add(msg); client.Publish(t.TopicName, messagesToAddToQueue); //committing to queue }
/// <summary>Snippet for Publish</summary> public void Publish() { // Snippet: Publish(TopicName,IEnumerable<PubsubMessage>,CallSettings) // Create client PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create(); // Initialize request argument(s) TopicName topic = new TopicName("[PROJECT]", "[TOPIC]"); IEnumerable <PubsubMessage> messages = new[] { new PubsubMessage { Data = Google.Protobuf.ByteString.CopyFromUtf8(""), }, }; // Make the request PublishResponse response = publisherServiceApiClient.Publish(topic, messages); // End snippet }
private static List <PubsubMessage> PublishMessages(PublisherServiceApiClient publisher, TopicName topicName) { List <PubsubMessage> unPublishedMessages = new List <PubsubMessage>(); //publish message to the topic for (int i = 0; i < 2; i++) { try { PubsubMessage pubsubMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8(i.ToString()), Attributes = { { "description", "Demo message" } } }; System.Threading.Thread.Sleep(1000); publisher.Publish(topicName, new[] { pubsubMessage }); Console.WriteLine("Published Message : " + i.ToString()); } catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == Grpc.Core.StatusCode.Unavailable) { Console.WriteLine("Some services are unavailable!! Will retry after some time."); unPublishedMessages.Add(new PubsubMessage() { Data = ByteString.CopyFromUtf8(i.ToString()), Attributes = { { "description", "Demo message" } } }); } catch (Exception ex) { Console.WriteLine("Add Error : " + ex.Message.ToString()); } } return(unPublishedMessages); }
public async Task PullAsync() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName(projectId, topicId); publisher.CreateTopic(topicName); PubsubMessage newMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8("Simple text") }; SubscriberServiceApiClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60); publisher.Publish(topicName, new[] { newMessage }); // Snippet: PullAsync(SubscriptionName,*,*,CallSettings) // Additional: PullAsync(SubscriptionName,*,*,CancellationToken) SubscriberServiceApiClient client = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(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 }
/// <summary>Snippet for Publish</summary> public void Publish_RequestObject() { // Snippet: Publish(PublishRequest,CallSettings) // Create client PublisherServiceApiClient publisherServiceApiClient = PublisherServiceApiClient.Create(); // Initialize request argument(s) PublishRequest request = new PublishRequest { TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage { Data = Google.Protobuf.ByteString.CopyFromUtf8(""), }, }, }; // Make the request PublishResponse response = publisherServiceApiClient.Publish(request); // End snippet }
private static void PubLishFile(string fileName) { try { PublisherServiceApiClient publishClient = PublisherServiceApiClient.Create(); var message = new QueueMessage() { FileName = fileName }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(message); publishClient.Publish(_topicName, new[] { new PubsubMessage() { Data = Google.Protobuf.ByteString.CopyFromUtf8(json) } }); } catch (Exception e) { _message = e.Message; } }
/// <summary> /// Publish method: uploads a message to the queue /// </summary> /// <param name="p"></param> public void AddToEmailQueue(FileSendTo p) { PublisherServiceApiClient client = PublisherServiceApiClient.Create(); var t = CreateGetTopic(); p.Link = KeyRepository.Encrypt(p.Link); p.OwnerFk = KeyRepository.Encrypt(p.OwnerFk); p.Message = KeyRepository.Encrypt(p.Message); p.Name = KeyRepository.Encrypt(p.Name); p.Email = KeyRepository.Encrypt(p.Email); string serialized = JsonSerializer.Serialize(p, typeof(FileSendTo)); List <PubsubMessage> messagesToAddToQueue = new List <PubsubMessage>(); // the method takes a list, so you can upload more than 1 message/item/product at a time PubsubMessage msg = new PubsubMessage(); msg.Data = ByteString.CopyFromUtf8(serialized); messagesToAddToQueue.Add(msg); client.Publish(t.TopicName, messagesToAddToQueue); //committing to queue }
//Publish method: uploads a message to the queue. public void AddToEmailQueue(File f, string recepient) { PublisherServiceApiClient client = PublisherServiceApiClient.Create(); Topic t = CreateGetTopic(); KeyRepository kr = new KeyRepository(); string serialized = JsonSerializer.Serialize(f, typeof(File)); // this list is used so that the method can take more than 1 message/item/file at a time. List <PubsubMessage> messagesToAddToQueue = new List <PubsubMessage>(); PubsubMessage msg = new PubsubMessage(); //Encripting data and recepient values string encryptedData = kr.Encrypt(serialized); string encryptedRecepient = kr.Encrypt(recepient); msg.Data = ByteString.CopyFromUtf8(encryptedData); //Stores email content. msg.Attributes["recepient"] = encryptedRecepient; //stores recepient as a key-value attribute. messagesToAddToQueue.Add(msg); client.Publish(t.TopicName, messagesToAddToQueue); //committing to queue }
public IEnumerable <string> PublishToTopic([FromBody] CreatTopicModel attr) { List <string> retorno = new List <string>(); try { var topicName = new TopicName(attr.projectId, attr.topicId); PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); // Create a message var message = new PubsubMessage() { Data = ByteString.CopyFromUtf8(attr.message) }; //message.Attributes.Add("myattrib", "its value"); var messageList = new List <PubsubMessage>() { message }; var response = publisher.Publish(topicName, messageList); foreach (string messageId in response.MessageIds) { retorno.Add(messageId); } } catch (Exception ex) { retorno.Add(ex.Message); return(retorno); } return(retorno); }
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(); }
static int Main(string[] args) { // Use a switch statement to do the math. Console.WriteLine("Pub or SubPull: "); switch (Console.ReadLine()) { case "Pub": Console.WriteLine("Message to Push: "); string mess = Console.ReadLine(); // First create a topic. PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName("pubSubfirst", "order_topic"); //publisher.CreateTopic(topicName); // // Publish a message to the topic. PubsubMessage message = new PubsubMessage { // The data is any arbitrary ByteString. Here, we're using text. Data = ByteString.CopyFromUtf8(mess), // The attributes provide metadata in a string-to-string dictionary. Attributes = { { "description", "Simple text message" } } }; publisher.Publish(topicName, new[] { message }); break; case "SubPull": // Subscribe to the topic. SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName("PubSubFirst", "orderTopicSubscr"); //subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60); subscriber.GetSubscription(subscriptionName, null); // 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); Console.WriteLine("Pull Response"); var msgnumber = response.ReceivedMessages.Count; Console.WriteLine(msgnumber); foreach (ReceivedMessage received in response.ReceivedMessages) { Console.WriteLine("Message:"); 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. if (response.ReceivedMessages.Count > 0) { subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId)); } break; } // Tidy up by deleting the subscription and the topic. //subscriber.DeleteSubscription(subscriptionName); //publisher.DeleteTopic(topicName); return(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 }