Connect to your cluster using the Java client

This document describes how to connect to a cluster through a Java client, and use the Java producer and consumer to produce and consume messages to and from a topic. The Java 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

  • Java 1.8 or higher version
  • Pulsar client 2.6.1 or higher version

Connect to your 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 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 Java client, see Java client examples.

Create a Java consumer to consume messages

You can create and configure a Java 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.

import java.net.URL;
import org.apache.pulsar.client.api.*;
import org.apache.pulsar.client.impl.auth.oauth2.AuthenticationFactoryOAuth2;

public class SNConsumer {

  public static void main(String[] args) throws Exception
  {
      String issuerUrl = "https://auth.streamnative.cloud/";
      String credentialsUrl = "{{ file://YOUR-KEY-FILE-PATH }}";
      String audience = "urn:sn:pulsar:${orgName}:${instanceName}";

      PulsarClient client = PulsarClient.builder()
          .serviceUrl("${brokerServiceURL}")
          .authentication(
                AuthenticationFactoryOAuth2.clientCredentials(new URL(issuerUrl),
                                                              new URL(credentialsUrl),
                                                              audience))
          .build();

      Consumer consumer = client.newConsumer()
              .topic("persistent://${tenant}/${namespace}/${topic}")
              .subscriptionName("${subscription}")
              .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)
              .subscribe();

      for (int i = 0; i < 10; i++) {
          Message<byte[]> msg = consumer.receive();
          consumer.acknowledge(msg);
          System.out.println("Receive message " + new String(msg.getData()));
      }

      consumer.close();
      client.close();

  }
}

Create a Java producer to produce messages

You can create and configure a Java 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.

import java.net.URL;
import org.apache.pulsar.client.api.*;
import org.apache.pulsar.client.impl.auth.oauth2.AuthenticationFactoryOAuth2;

public class SNProducer {

  public static void main(String[] args) throws Exception
  {

      String issuerUrl = "https://auth.streamnative.cloud/";
      String credentialsUrl = "file:///YOUR-KEY-FILE-PATH"; // Absolute path of your downloaded key file
      String audience = "urn:sn:pulsar:${orgName}:${instanceName}";

      PulsarClient client = PulsarClient.builder()
          .serviceUrl("${brokerServiceURL}")
          .authentication(
                AuthenticationFactoryOAuth2.clientCredentials(new URL(issuerUrl),
                                                              new URL(credentialsUrl),
                                                              audience))
          .build();

      Producer<byte[]> producer = client.newProducer()
          .topic("persistent://${tenant}/${namespace}/${topic}")
          .create();

      for (int i = 0; i < 10; i++) {
          String message = "my-message-" + i;
          MessageId msgID = producer.send(message.getBytes());
          System.out.println("Publish " + "my-message-" + i
                             + " and message ID " + msgID);
      }

      producer.close();
      client.close();
  }
}

Parameters for OAuth2 authentication

  • credentialsUrl: 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 Pulsar 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.

Connect to your 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 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 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.
  • 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.

To get a token using 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 Token column, click Generate new token, then click the Copy icon to copy the token to your clipboard.

Step 3: Connect to your cluster

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

Create a Java consumer to consume messages

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

import java.net.URL;
import org.apache.pulsar.client.api.*;

public class SNConsumer {

    public static void main(String[] args) throws Exception
    {

        PulsarClient client = PulsarClient.builder()
            .serviceUrl("${brokerServiceURL}")
            .authentication(
                AuthenticationFactory.token("${token}")
            )
            .build();

        Consumer consumer = client.newConsumer()
                .topic("persistent://${tenant}/${namespace}/${topic}")
                .subscriptionName("${subscription}")
                .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)
                .subscribe();

        for (int i = 0; i < 10; i++) {
            Message<byte[]> msg = consumer.receive();
            consumer.acknowledge(msg);
            System.out.println("Receive message " + new String(msg.getData()));
        }

        consumer.close();
        client.close();

    }

}

Create a Java producer to produce messages

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

import java.net.URL;
import org.apache.pulsar.client.api.*;

public class SNProducer {

    public static void main(String[] args) throws Exception
    {

        PulsarClient client = PulsarClient.builder()
            .serviceUrl("${brokerServiceURL}")
            .authentication(
                AuthenticationFactory.token("${token}")
            )
            .build();

        Producer<byte[]> producer = client.newProducer()
            .topic("persistent://${tenant}/${namespace}/${topic}")
            .create();

        for (int i = 0; i < 10; i++) {
            String message = "my-message-" + i;
            MessageId msgID = producer.send(message.getBytes());
            System.out.println("Publish " + "my-message-" + i
                               + " and message ID " + msgID);
        }

        producer.close();
        client.close();

    }

}

Parameters for Token authentication

  • ${brokerServiceURL}: the broker service URL of your Pulsar cluster.
  • ${token}: the token 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.
Previous
Go