简体   繁体   中英

How to Implement Spark Streaming Output with Sockets

I've been trying to implement this in Java:

dstream.foreachRDD { rdd =>
  rdd.foreachPartition { partitionOfRecords =>
    val connection = createNewConnection()
    partitionOfRecords.foreach(record => connection.send(record))
    connection.close()
  }
}

for the types of examples that the Spark documentation provides. The following works as expected:

import scala.Tuple2;
import com.google.common.collect.Lists;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.StorageLevels;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.streaming.Time;

import java.util.regex.Pattern;
import java.io.IOException;

/**
* Counts words in UTF8 encoded, '\n' delimited text received from the network every second.
*
* Usage: JavaNetworkWordCount <hostname> <port>
* <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive data.
*
* To run this on your local machine, you need to first run a Netcat server
*    `$ nc -lk 9999`
* and then run the example
*    `$ bin/run-example org.apache.spark.examples.streaming.JavaNetworkWordCount localhost 9999`
*/
public final class SocketWriter {
  private static final Pattern SPACE = Pattern.compile(" ");

  public static void main(String[] args) {
    if (args.length < 2) {
      System.err.println("Usage: JavaNetworkWordCount <hostname> <port>");
      System.exit(1);
    }

    // Create the context with a 1 second batch size
    SparkConf sparkConf = new SparkConf().setAppName("JavaNetworkWordCount");
    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));

    // Create a JavaReceiverInputDStream on target ip:port and count the
    // words in input stream of \n delimited text (eg. generated by 'nc')
    // Note that no duplication in storage level only for running locally.
    // Replication necessary in distributed scenario for fault tolerance.
    JavaReceiverInputDStream<String> lines = ssc.socketTextStream(
    args[0], Integer.parseInt(args[1]), StorageLevels.MEMORY_AND_DISK_SER);
    JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
      @Override
      public Iterable<String> call(String x) {
        return Lists.newArrayList(SPACE.split(x));
      }
    });
    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
    new PairFunction<String, String, Integer>() {
      @Override
      public Tuple2<String, Integer> call(String s) {
        return new Tuple2<String, Integer>(s, 1);
      }
    }).reduceByKey(new Function2<Integer, Integer, Integer>() {
      @Override
      public Integer call(Integer i1, Integer i2) {
        return i1 + i2;
      }
    });

    wordCounts.foreachRDD(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {
      @Override
      public Void call(JavaPairRDD<String, Integer> rdd, Time time) throws IOException {
        String counts = "Counts at time " + time + " " + rdd.collect();
        System.out.println(counts);
        return null;
      }
    });

    ssc.start();
    ssc.awaitTermination();
  }
}

But I need to be able to output data to a socket by modifying this section to use the "design pattern" specified in Scala at the top of this question.

wordCounts.foreachRDD(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {
  @Override
  public Void call(JavaPairRDD<String, Integer> rdd, Time time) throws IOException {
    String counts = "Counts at time " + time + " " + rdd.collect();
    System.out.println(counts);
    return null;
  }
});

I tried to use Socket and PrintWriter objects here, but cannot make it work, and I can't find any examples of people doing this. Any help is appreciated.

I just show you question as I was trying to do the same, and finally I have done it! Probably is too late for you, but hope not for many other people.

As here in the official documentation says, I have not done it in the most optimal way, which is using a pool of connections so Spark would not have to open and close the connection for every RDD, but is still working, here is my code:

wordCounts.foreachRDD(new VoidFunction<JavaRDD<String>>() {
    public void call(JavaRDD<String> rdd) throws Exception {
        rdd.foreachPartition(new VoidFunction<Iterator<String>>() {
            public void call(Iterator<String> partitionOfRecords) throws Exception {
                Socket mySocket = new Socket("localhost", 9998);
                final PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);
                while(partitionOfRecords.hasNext()) {
                    out.println(partitionOfRecords.next());
                }
                mySocket.close();
            }
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM