Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Last active December 16, 2022 13:56
Show Gist options
  • Save yetanotherchris/ea4f0858cd830e72c2ed8b941d2c6faf to your computer and use it in GitHub Desktop.
Save yetanotherchris/ea4f0858cd830e72c2ed8b941d2c6faf to your computer and use it in GitHub Desktop.
Google Cloud Pub/Sub C# example
//
// Google Cloud Pub/Sub C# example
// NOTE: This is a .NET Core 1.1 console app.
// Use "dotnet run" to run it, run setup.ps1 first.
//
using System;
using System.Collections.Generic;
using Google.Cloud.PubSub.V1;
using Google.Protobuf;
using Grpc.Core;
namespace PubSubExample
{
public class ProgramExample
{
private const string ProjectId = "YOUR PROJECT ID";
private const string TopicId = "YOUR TOPIC ID";
private const string SubscriptionId = "YOUR SUBSCRIPTION ID";
// To view a message in your subscription:
// gcloud beta pubsub subscriptions pull testsub1
public static void Main(string[] args)
{
PublishToTopic();
PublishToTopic();
// The loop is necessary as pull doesn't always brings back all your messages
var response = ShowMessagesForSubscription();
while (response != null && response.ReceivedMessages.Count > 0)
{
response = ShowMessagesForSubscription();
}
}
private static void CreateTopic()
{
// The fully qualified name for the new topic
var topicName = new TopicName(ProjectId, TopicId);
// Creates the new topic
PublisherClient publisher = PublisherClient.Create();
Topic topic = publisher.CreateTopic(topicName);
Console.WriteLine($"Topic {topic.Name} created.");
}
private static void ListTopics()
{
// List all topics for the project
PublisherClient publisher = PublisherClient.Create();
var topics = publisher.ListTopics(new ProjectName(ProjectId));
foreach (Topic topic1 in topics)
{
Console.WriteLine(topic1.Name);
}
}
private static void PublishToTopic()
{
var topicName = new TopicName(ProjectId, TopicId);
PublisherClient publisher = PublisherClient.Create();
// Create a message
var message = new PubsubMessage()
{
Data = ByteString.CopyFromUtf8("hello world")
};
message.Attributes.Add("myattrib", "its value");
// Add it to the list of messages to publish
var messageList = new List<PubsubMessage>() { message };
// Publish it
Console.WriteLine("Publishing...");
var response = publisher.Publish(topicName, messageList);
// Get the message ids GCloud gave us
Console.WriteLine(" Message ids published:");
foreach (string messageId in response.MessageIds)
{
Console.WriteLine($" {messageId}");
}
}
private static PullResponse ShowMessagesForSubscription()
{
var subscriptionName = new SubscriptionName(ProjectId, SubscriptionId);
var subscription = SubscriberClient.Create();
try
{
PullResponse response = subscription.Pull(subscriptionName, true, 10);
var all = response.ReceivedMessages;
foreach (ReceivedMessage message in all)
{
string id = message.Message.MessageId;
string publishDate = message.Message.PublishTime.ToDateTime().ToString("dd-M-yyyy HH:MM:ss");
string data = message.Message.Data.ToStringUtf8();
Console.WriteLine($"{id} {publishDate} - {data}");
Console.Write(" Acknowledging...");
subscription.Acknowledge(subscriptionName, new string[] { message.AckId });
Console.WriteLine("done");
}
return response;
}
catch (RpcException e)
{
Console.WriteLine("Something went wrong: {0}", e.Message);
return null;
}
}
}
}
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {
"Google.Cloud.PubSub.V1": "1.0.0-beta06",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0"
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
},
"imports": "dnxcore50"
}
}
}
#
# Once you have a Google cloud account setup:
#
# 1. Download and install the Google Cloud Windows SDK
# 2. Inside the browser, download a credentials.json file
# 3. Put the .json file inside the directory you run this example.
# 4. Run "gcloud components install beta"
# 5. Update the project and zone inside this script.
# 6. Run this script before performing a "dotnet run"
#
$env:HOME="$(pwd)"
$env:GOOGLE_APPLICATION_CREDENTIALS="$(pwd)\google-cloud-credentials.json"
$project="YOUR-PROJECT-ID"
$zone="europe-west1-b"
gcloud config set compute/zone $zone
gcloud config set project $project
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment