1. Build Applications
  2. Pulsar Client Guides

Connect to your cluster using the C# client

This document describes how to connect to a cluster through a C# client, and use the C# producer and consumer to produce and consume messages to and from a topic. The C# client supports connecting to a Pulsar cluster through either OAuth2 or Token authentication.

Note

This document assumes that you have created a Pulsar cluster and a service account, and have granted the service account produce and consume permissions to the namespace for the target topic.

Prerequisites

Install Pulsar client 2.4 or higher versions.

Connect to cluster through OAuth2 authentication

To connect a Pulsar cluster through OAuth2 authentication, follow these steps.

Step 1: Get the broker service URL of your cluster

To get the service URL of a Pulsar cluster through the StreamNative Cloud Console, follow these steps.

  1. On the left navigation pane, in the Admin area, click Pulsar Clusters.

  2. Select the Overview tab, and in the Access Points area, click Copy at the end of the row of the service URL.

Step 2: Get the OAuth2 credential file of your service account

To get an OAuth2 credential file of a service account through the StreamNative Cloud Console, follow these steps.

  1. On the left navigation pane, click Service Accounts.

  2. In the row of the service account you want to use, in the Key File column, click the Download icon to download the OAuth2 credential file to your local directory.

    The OAuth2 credential file should be something like this:

    {
      "type": "SN_SERVICE_ACCOUNT",
      "client_id": "CLIENT_ID",
      "client_secret": "CLIENT_SECRET",
      "client_email": "[email protected]",
      "issuer_url": "https://auth.streamnative.cloud"
    }
    

Step 3: Connect to your cluster

   client = await new PulsarClientBuilder()
             .ServiceUrl(serviceUrl)
             .Authentication(AuthenticationFactoryOAuth2.ClientCredentials(issuerUrl, audience, fileUri))
             .BuildAsync();
  • serviceUrl: the broker service URL of your Pulsar cluster.
  • issuerUrl: the URL of your OAuth2 authentication provider. You can get the value from your downloaded OAuth2 credential file.
  • fileUri: the path to your downloaded OAuth2 credential file. The fileUri parameter supports the following three pattern formats:
    • file:///path/to/file
    • file:/path/to/file
    • data:application/json;base64,<base64-encoded value>
  • audience: the audience parameter is the Uniform Resource Name (URN), which is a combination of the urn:sn:pulsar, the organization name, and the Pulsar instance name, in this format urn:sn:pulsar:<org_name>:<instance_name>.

Create a C# consumer to consume messages

 using System;
 using System.IO;
 using System.Reflection;
 using System.Text;
 using System.Threading.Tasks;
 using Pulsar.Client.Api;
 using Pulsar.Client.Common;

 namespace CsharpExamples
 {
     internal class Oauth2
     {
         internal static async Task RunOauth()
         {
             var fileUri = new Uri("{{ file://YOUR-KEY-FILE-PATH }}");
             var issuerUrl = new Uri("https://auth.streamnative.cloud/");
             var audience = "{{ YOUR-AUDIENCE }}";

             const string serviceUrl = "{{ SERVICE_URL }}";
             var topicName = "persistent://public/default/test-topic";
             const string subscriptionName = "test-sub";

             var client = await new PulsarClientBuilder()
                 .ServiceUrl(serviceUrl)
                 .Authentication(AuthenticationFactoryOAuth2.ClientCredentials(issuerUrl, audience, fileUri))
                 .BuildAsync();

             var consumer = await client.NewConsumer()
                 .Topic(topicName)
                 .SubscriptionName(subscriptionName)
                 .SubscribeAsync();

             for(int i=0; i< 10; i++){
                 var message = await consumer.ReceiveAsync();
                 Console.WriteLine($"Received: {Encoding.UTF8.GetString(message.Data)}");

                 await consumer.AcknowledgeAsync(message.MessageId);
             }
         }
     }
 }

Create a C# producer to produce messages

 using System;
 using System.IO;
 using System.Reflection;
 using System.Text;
 using System.Threading.Tasks;
 using Pulsar.Client.Api;
 using Pulsar.Client.Common;

 namespace CsharpExamples
 {
     internal class Oauth2
     {
         internal static async Task RunOauth()
         {
             var fileUri = new Uri("{{ file://YOUR-KEY-FILE-PATH }}");
             var issuerUrl = new Uri("https://auth.streamnative.cloud/");
             var audience = "{{ YOUR-AUDIENCE }}";

             const string serviceUrl = "{{ SERVICE_URL }}";
             var topicName = "persistent://public/default/test-topic";

             var client = await new PulsarClientBuilder()
                 .ServiceUrl(serviceUrl)
                 .Authentication(AuthenticationFactoryOAuth2.ClientCredentials(issuerUrl, audience, fileUri))
                 .BuildAsync();

             var producer = await client.NewProducer()
                 .Topic(topicName)
                 .CreateAsync();

             for(int i=0; i< 10; i++){
                 var messageId = await producer.SendAsync(Encoding.UTF8.GetBytes($"Sent from C# at '{DateTime.Now}'"));
                 Console.WriteLine($"MessageId is: '{messageId}'");
             }
         }
     }
 }

Connect to cluster through Token authentication

To connect a Pulsar cluster through Token authentication, follow these steps.

Step 1: Get the broker service URL of your cluster

To get the service URL of a Pulsar cluster through the StreamNative Cloud Console, follow these steps.

  1. On the left navigation pane, in the Admin area, click Pulsar Clusters.

  2. Select the Overview tab, and in the Access Points area, click Copy at the end of the row of the service URL.

Step 2: Get the Token of your service account

Note

Before getting the token of a service account, verify that the service account is authorized as a superuser or an admin of the tenants and namespaces.

To get a token using the StreamNative Cloud Console, follow these steps.

  1. On the left navigation pane, click Service Accounts.

  2. In the row of the service account you want to use, in the Token column, click Generate new token, then click the Copy icon to copy the token to your clipboard.

Note

A token has a system-defined Time-To-Live (TTL) of 7 days. Before a token expires, ensure that you generate a new token for your service account.

Step 3: Connect to your cluster

   client = await new PulsarClientBuilder()
             .ServiceUrl(serviceUrl)
             .Authentication(AuthenticationFactory.Token(token))
             .BuildAsync();
  • serviceUrl: the broker service URL of your Pulsar cluster.
  • token: the token of your service account.

For a complete example about how to connect to a cluster through the C# client, see C# client examples.

Previous
Overview