spark streaming 2 streaming on RDD

复制代码
package com.shujia.spark.streaming

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo2StreamOnRDD {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession.builder()
      .appName("streaming")
      .master("local[2]")
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()

    import spark.implicits._
    import org.apache.spark.sql.functions._

    val sc: SparkContext = spark.sparkContext

    /**
      * 创建streaming 上下文对象,指定batch的间隔时间,多久计算一次
      *
      */
    val ssc = new StreamingContext(sc, Durations.seconds(5))

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
      * foreachRDD:将DS转换成RDD使用,可以使用 rdd 的 api
      *
      */
    linesDS.foreachRDD(rdd => {
      /**
        * 每个batch计算一次,不能做全局的计算
        *
        */

      //使用rdd api
      rdd.flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)
//        .foreach(println)

      val lineDF: DataFrame = rdd.toDF("lines")

      lineDF
        .select(explode(split($"lines", ",")) as "word")
        .groupBy($"word")
        .agg(count($"word") as "C")
      // .show()

      lineDF.createOrReplaceTempView("words")


      spark.sql(
        """
          |
          |select word,count(1) from (
          |select explode(split(lines,',')) as word from words
          |) as a
          |group by word
          |
        """.stripMargin)
        .show()

    })

    //启动streaming
    ssc.start()
    ssc.awaitTermination() //等待关闭    这三行代码必须要写
    ssc.stop()


  }
}
复制代码

 

posted @   坤坤无敌  阅读(42)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示