1. Build Applications
  2. Pulsar Clients

Connect to your cluster using the Pulsar C++ client

This document describes how to connect to a cluster using 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 StreamNative cluster using either OAuth2 or API Keys authentication.

Note

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

Connect to your cluster using API keys

To connect a StreamNative cluster using API keys, 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 Console, follow these steps.

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

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

Step 2: Create an API key of your service account

Note

Before using an API key, verify that the service account is authorized to access the resources, such as tenants, namespaces, and topics.

You can follow the instructions to create an API key for the service account you choose to use.

Step 3: Connect to your cluster

For a complete example of how to connect to a cluster using the Pulsar C++ client, see C++ client examples.

Create a C++ consumer to consume messages

You can create and configure a C++ consumer to consume messages using Token authentication as follows. For more information about the placeholders in the code sample, see parameters for Token authentication.

#include <pulsar/Client.h>
#include <thread>

using namespace pulsar;

int main() {
    ClientConfiguration clientConfig;
    clientConfig.setAuth(AuthToken::createWithToken("${apikey}"));
    Client client("${brokerServiceURL}", clientConfig);

    Consumer consumer;
    ConsumerConfiguration consumerConfig;
    consumerConfig.setSubscriptionInitialPosition(InitialPositionEarliest);
    Result result = client.subscribe("persistent://${tenant}/${namespace}/${topic}", "${subscription}", consumerConfig, consumer);
    if (result != ResultOk) {
        std::cout << "Failed to subscribe: " << result << std::endl;
        return -1;
    }

    Message msg;
    int ctr = 0;

    while (ctr < 10) {
        consumer.receive(msg);
        std::cout << "Received: " << msg
            << "  with payload '" << msg.getDataAsString() << "'" << std::endl;

        consumer.acknowledge(msg);
        ctr++;
    }

    std::cout << "Finished consuming synchronously!" << std::endl;

    client.close();
    return 0;
}

Create a C++ producer to produce messages

You can create and configure a C++ producer to produce messages using Token authentication as follows. For more information about the placeholders in the code sample, see parameters for Token authentication.

#include <pulsar/Client.h>
#include <thread>

using namespace pulsar;

int main() {
    ClientConfiguration config;
    config.setAuth(AuthToken::createWithToken("${apikey}"));
    Client client("${brokerServiceURL}", config);

    Producer producer;
    Result result = client.createProducer("persistent://${tenant}/${namespace}/${topic}", producer);
    if (result != ResultOk) {
        std::cout << "Error creating producer: " << result << std::endl;
        return -1;
    }

    int ctr = 0;
    while (ctr < 10) {
        std::string content = "msg" + std::to_string(ctr);
        Message msg = MessageBuilder().setContent(content).setProperty("x", "1").build();
        Result result = producer.send(msg);
        if (result != ResultOk) {
            std::cout << "The message " << content << " could not be sent, received code: " << result << std::endl;
        } else {
            std::cout << "The message " << content << " sent successfully" << std::endl;
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        ctr++;
    }

    std::cout << "Finished producing synchronously!" << std::endl;

    client.close();
    return 0;
}

Parameters for Token authentication

  • ${brokerServiceURL}: the broker service URL of your StreamNative cluster.
  • ${apikey}: an API key of your service account.
  • ${tenant}/${namespace}/${topic}: the full name of the topic for message production & consumption. It is a combination of the tenant name, the namespace name and the topic name.
  • ${subscription}: the name of the subscription that will determine how messages are delivered.

Connect to your cluster using OAuth2 authentication

To connect a StreamNative cluster using 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 Console, follow these steps.

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

  2. Select the Details 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 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

For a complete example of how to connect to a cluster through the Pulsar C++ client, see C++ client examples.

Create a C++ consumer to consume messages

You can create and configure a C++ consumer to consume messages using the OAuth2 credential file as follows. For more information about the placeholders in the code sample, see parameters for OAuth2 authentication.

#include <pulsar/Client.h>
#include <thread>

using namespace pulsar;

int main() {
    ClientConfiguration clientConfig;
     // Replace YOUR-KEY-FILE-PATH with the absolute path or your downloaded JSON key file:
   std::string params = R"({
    "issuer_url": "https://auth.streamnative.cloud/",
    "private_key": "{{ file://YOUR-KEY-FILE-PATH }}",
    "audience": "urn:sn:pulsar:${orgName}:${instanceName}"})";

    clientConfig.setAuth(pulsar::AuthOauth2::create(params));
    Client client("${brokerServiceURL}", clientConfig);

    Consumer consumer;
    ConsumerConfiguration consumerConfig;
    consumerConfig.setSubscriptionInitialPosition(InitialPositionEarliest);
    Result result = client.subscribe("persistent://${tenant}/${namespace}/${topic}", "${subscription}", consumerConfig, consumer);
    if (result != ResultOk) {
        std::cout << "Failed to subscribe: " << result << std::endl;
        return -1;
    }

    Message msg;
    int ctr = 0;

    while (ctr < 10) {
        consumer.receive(msg);
        std::cout << "Received: " << msg
            << "  with payload '" << msg.getDataAsString() << "'" << std::endl;

        consumer.acknowledge(msg);
        ctr++;
    }

    std::cout << "Finished consuming synchronously!" << std::endl;

    client.close();
    return 0;
}

Create a C++ producer to produce messages

You can create and configure a C++ producer to produce messages using the OAuth2 credential file as follows. For more information about the placeholders in the code sample, see parameters for OAuth2 authentication.

#include <pulsar/Client.h>
#include <thread>

using namespace pulsar;

int main() {
    ClientConfiguration config;
    // Replace YOUR-KEY-FILE-PATH with the absolute path or your downloaded JSON key file:
    std::string params = R"({
    "issuer_url": "https://auth.streamnative.cloud/",
    "private_key": "/YOUR-KEY-FILE-PATH",
    "audience": "urn:sn:pulsar:${orgName}:${instanceName}"})";

    config.setAuth(pulsar::AuthOauth2::create(params));
    Client client("${brokerServiceURL}", config);

    Producer producer;
    Result result = client.createProducer("persistent://${tenant}/${namespace}/${topic}", producer);
    if (result != ResultOk) {
        std::cout << "Error creating producer: " << result << std::endl;
        return -1;
    }

    int ctr = 0;
    while (ctr < 10) {
        std::string content = "msg" + std::to_string(ctr);
        Message msg = MessageBuilder().setContent(content).setProperty("x", "1").build();
        Result result = producer.send(msg);
        if (result != ResultOk) {
            std::cout << "The message " << content << " could not be sent, received code: " << result << std::endl;
        } else {
            std::cout << "The message " << content << " sent successfully" << std::endl;
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        ctr++;
    }

    std::cout << "Finished producing synchronously!" << std::endl;

    client.close();
    return 0;
}

Parameters for OAuth2 authentication

  • private_key: your downloaded OAuth2 credential. This parameter supports the following two pattern formats:
    • file:///path/to/file: the path to your downloaded OAuth2 credential file.
    • data:application/json;base64,<base64-encoded value>: the credential file content encoded into Base64 format.
  • audience: the Uniform Resource Name (URN), which is a combination of the urn:sn:pulsar, your organization name, and your Pulsar instance name.
  • ${brokerServiceURL}: the broker service URL of your StreamNative cluster.
  • ${tenant}/${namespace}/${topic}: the full name of the topic for message production & consumption. It is a combination of the tenant name, the namespace name and the topic name.
  • ${subscription}: the name of the subscription that will determine how messages are delivered.
Previous
C#
Next
Go