Pulsar adaptor for Apache Spark

Spark Streaming receiver

The Spark Streaming receiver for Pulsar is a custom receiver that enables Apache Spark Streaming to receive raw data from Pulsar.

An application can receive data in Resilient Distributed Dataset (RDD) format via the Spark Streaming receiver and can process it in a variety of ways.

Prerequisites

To use the receiver, include a dependency for the pulsar-spark library in your Java configuration.

Maven

If you’re using Maven, add this to your pom.xml:

  1. <!-- in your <properties> block -->
  2. <pulsar.version>3.1.1</pulsar.version>
  3. <!-- in your <dependencies> block -->
  4. <dependency>
  5. <groupId>org.apache.pulsar</groupId>
  6. <artifactId>pulsar-spark</artifactId>
  7. <version>${pulsar.version}</version>
  8. </dependency>

Gradle

If you’re using Gradle, add this to your build.gradle file:

  1. def pulsarVersion = "3.1.1"
  2. dependencies {
  3. compile group: 'org.apache.pulsar', name: 'pulsar-spark', version: pulsarVersion
  4. }

Usage

Pass an instance of SparkStreamingPulsarReceiver to the receiverStream method in JavaStreamingContext:

  1. String serviceUrl = "pulsar://localhost:6650/";
  2. String topic = "persistent://public/default/test_src";
  3. String subs = "test_sub";
  4. SparkConf sparkConf = new SparkConf().setMaster("local[*]").setAppName("Pulsar Spark Example");
  5. JavaStreamingContext jsc = new JavaStreamingContext(sparkConf, Durations.seconds(60));
  6. ConsumerConfigurationData<byte[]> pulsarConf = new ConsumerConfigurationData();
  7. Set<String> set = new HashSet();
  8. set.add(topic);
  9. pulsarConf.setTopicNames(set);
  10. pulsarConf.setSubscriptionName(subs);
  11. SparkStreamingPulsarReceiver pulsarReceiver = new SparkStreamingPulsarReceiver(
  12. serviceUrl,
  13. pulsarConf,
  14. new AuthenticationDisabled());
  15. JavaReceiverInputDStream<byte[]> lineDStream = jsc.receiverStream(pulsarReceiver);

For a complete example, click here. In this example, the number of messages that contain the string “Pulsar” in received messages is counted.

Note that if needed, other Pulsar authentication classes can be used. For example, to use a token during authentication the following parameters for the SparkStreamingPulsarReceiver constructor can be set:

  1. SparkStreamingPulsarReceiver pulsarReceiver = new SparkStreamingPulsarReceiver(
  2. serviceUrl,
  3. pulsarConf,
  4. new AuthenticationToken("token:<secret-JWT-token>"));