[英]Can Apache Spark use TCP listener as input?
Apache Spark可以使用TCP偵聽器作為輸入嗎? 如果是,則可能有人提供了執行該操作的Java代碼示例。
我嘗試查找有關此示例,但是所有教程都展示了如何通過TCP而不是使用等待傳入數據的TCP偵聽器來定義到數據服務器的輸入連接。
是的,可以使用Spark偵聽TCP端口並處理所有傳入的數據。 您正在尋找的是Spark Streaming 。
在文檔和github上有一個小指南可以監聽TCP源代碼。 為了方便:
import org.apache.spark.*;
import org.apache.spark.api.java.function.*;
import org.apache.spark.streaming.*;
import org.apache.spark.streaming.api.java.*;
import scala.Tuple2;
// Create a local StreamingContext with two working thread and batch interval of 1 second
SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount");
JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(1));
// Create a DStream that will connect to hostname:port, like localhost:9999
JavaReceiverInputDStream<String> lines = jssc.socketTextStream("localhost", 9999);
// Split each line into words
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split(" ")).iterator());
// Count each word in each batch
JavaPairDStream<String, Integer> pairs = words.mapToPair(s -> new Tuple2<>(s, 1));
JavaPairDStream<String, Integer> wordCounts = pairs.reduceByKey((i1, i2) -> i1 + i2);
// Print the first ten elements of each RDD generated in this DStream to the console
wordCounts.print();
jssc.start(); // Start the computation
jssc.awaitTermination(); // Wait for the computation to terminate
Spark沒有內置的TCP服務器來等待生產者和緩沖數據。 Spark通過其API庫在TCP,Kafka等的輪詢機制上工作。要消耗傳入的TCP數據,您需要具有外部TCP服務器,Spark可以連接到該外部服務器,如Shaido在示例中所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.