Spark Streaming wordcount(java程序发送请求)

要求:将nc -lk 9999指令用Java的ServerSocket实现:即通过Java程序实现ServerSocket的9999端监听,作为Spark Streaming的Socket流,用户可以通过控制台输入信息后发送给Sparkstreaming进行处理。

 

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SparkStreamingTest {
    public static void main(String args[])  {
        sendTCP();
    }
    public static void sendTCP()  {
        try {
            int port = 9999;
            ServerSocket server = new ServerSocket(port);
            //只有服务器被客户端连接后才会执行后面的语句
            System.out.println("服务器正在监听");
            Socket client = server.accept();
            System.out.println(client.getInetAddress() + "已建立连接! ");
            //输入流
            //  InputStream is = client.getInputStream();
            //使用System.in 创建BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            //输出流
            OutputStream os = client.getOutputStream();
            PrintWriter pw = new PrintWriter(os,true);
            System.out.println("Enter lines of text.");
            String str;
            do {
                str = br.readLine();

                // PrintWriter把数据写到目的地
                pw.println(str);
                System.out.println(str);
            } while (!str.equals("end"));

        } catch (Exception e) {
            System.out.println("connection exit!");
            System.out.println();
        }
    }
}
import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * @官方入门案例a-quick-example: http://spark.apache.org/docs/latest/streaming-programming-guide.html#a-quick-example
 */
object NetworkWordCount {
  def main(args: Array[String]): Unit = {
    //0编程入口StreamingContext:A StreamingContext object can be created from a SparkConf object.
    val conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount")
    //实时数据分析环境对象
    //以指定的时间为周期采集实时数据
    val ssc = new StreamingContext(conf, Seconds(4))

    // 1.Define the input sources by creating input DStreams.
    // Create a DStream that will connect to hostname:port, like localhost:9999
    //从指定端口中采集数据
    val lines:ReceiverInputDStream[String] = ssc.socketTextStream("127.0.0.1", 9999)

    // 2.Define the streaming computations by applying transformation and output operations to DStreams.
    // Split each line into words
    //将采集的数据进行分解
    val words = lines.flatMap(_.split(" "))
    import org.apache.spark.streaming.StreamingContext._ // not necessary since Spark 1.3
    // Count each word in each batch
    //将转换结构后的数据进行聚合处理map
    val pairs = words.map(word => (word, 1))
    val wordCounts = pairs.reduceByKey(_ + _)

    // Print the first ten elements of each RDD generated in this DStream to the console
    wordCounts.print()


    // 3.Start receiving data and processing it using streamingContext.start().
    ssc.start()             // Start the computation

    // 4. Wait for the processing to be stopped (manually or due to any error) using streamingContext.awaitTermination().
    ssc.awaitTermination()  // Wait for the computation to terminate

    // 5不会被执行. The processing can be manually stopped using streamingContext.stop().
    ssc.stop(true)
  }

}

### Spark 和 Flink 的核心区别及适用场景 #### 架构与设计理念 Apache Spark 和 Apache Flink 是目前最流行的两大分布式计算框架,二者的设计理念存在显著差异。Spark 更加注重通用性和灵活性,适用于多种类型的批量和交互式查询任务[^4]。相比之下,Flink 则专注于高吞吐量、低延迟的流处理能力,并提供了更加完善的事件时间支持以及精确一次的状态管理机制[^2]。 #### 数据处理模式 - **Spark**: 主要是基于微批处理的方式运作,即使是在 Structured Streaming 中也是如此。这意味着输入数据会被分割成固定大小的小批次来进行连续不断的增量式计算[^3]。 - **Flink**: 实现了真正的持续流处理模型,可以直接对每一条到达的数据记录执行即时运算,无需等待整个批次收集完毕后再统一处理[^1]。 #### 性能表现 - 在短作业启动速度方面,由于 Flink 不需要经历复杂的 DAG 调度过程,所以往往比 Spark 更快响应临时请求- 对于长时间运行的任务而言,得益于其原生支持的 checkpointing 功能,使得恢复成本更低且稳定性更强。 #### 编程接口友好度 两者都提供了丰富的 API 层面选项给开发者使用,包括但不限于 Scala/Python/R 等高级语言绑定形式。但从易用性的角度来看,初学者可能会觉得 Spark SQL 或者 DataFrame 接口更为直观简单一些;而对于那些追求极致效率或者定制化逻辑实现的人来说,则更倾向于利用 ProcessFunction 来编写自定义业务规则下的复杂转换操作。 #### 应用场景举例 | 场景描述 | 推荐工具 | | --- | --- | | 批量历史数据分析报表生成 | Spark (借助RDD, Dataset APIs)| | 实时广告点击率预测服务搭建 | Flink (凭借CEP Library & Stateful Processing Capabilities) | --- ```scala // 示例代码展示了如何在Scala中创建简单的WordCount应用程序分别用Spark RDD API(ForkJoinPool parallelism implied by default) 和Flink DataSet API(Explicit Parallelism setting). import org.apache.spark.{SparkConf, SparkContext} object WordCountWithSpark { def main(args: Array[String]): Unit = { val conf = new SparkConf().setAppName("wordcount").setMaster("local[*]") val sc = new SparkContext(conf) val textFile = sc.textFile("/input/path/to/textfile") val wordCounts = textFile.flatMap(_.split("\\s+")) .map(word => (word, 1)) .reduceByKey(_ + _) wordCounts.saveAsTextFile("/output/directory/") sc.stop() } } ``` ```java // Correspondingly implemented via Apache Flink's DataStream API. import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.util.Collector; public class WordCountWithFlink { public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.socketTextStream("localhost", 9999) .flatMap(new Tokenizer()) .keyBy(value -> value.f0) .sum(1) .print(); env.execute("Socket Text Stream Word Count Example"); } public static final class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> { @Override public void flatMap(String sentence, Collector<Tuple2<String, Integer>> out) { for (String word : sentence.toLowerCase().split("\\W+")) { if (word.length() > 0) { out.collect(new Tuple2<>(word, 1)); } } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值