spark使用window来统计近几分钟数据情况

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29493353/article/details/84973271
package com.xyf
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}


object sparkStreamingTest {
  def main(args: Array[String]){

    val conf = new SparkConf() //创建SparkConf对象
    conf.setAppName("sparkStreamingTest") //设置应用程序的名称,在程序运行的监控界面可以看到名称
    conf.setMaster("local[3]") //此时,程序在Spark集群

    /*
    * 此处设置 Batch Interval 实在spark Streaming 中生成基本Job的单位,窗口和滑动时间间隔
    * 一定是该batch Interval的整数倍*/
    val ssc = new StreamingContext(conf, Seconds(5))

    val hottestStream = ssc.socketTextStream("192.168.0.100", 9999)



    val searchPair = hottestStream.flatMap(line => line.split(",")).map(item => (item , 1))
    //reducefunction计算每个rdd的和,60s是窗口,20是滑动步长
    val hottestDStream = searchPair.reduceByKeyAndWindow((v1:Int,v2:Int) => v1 + v2, Seconds(60) ,Seconds(20))

    hottestDStream.transform(hottestItemRDD => {
      //将pair._2,pair._1反过来,通过数字来排序,然后反转,最终获取前三个打印
      val top3 =  hottestItemRDD.map(pair => (pair._2,pair._1) ).sortByKey(false).
        map(pair => (pair._2,pair._1)).take(3)

      for(item <- top3){
        println(item)
      }
      hottestItemRDD
    }).print()
    ssc.start()
    ssc.awaitTermination()

  }
}

windows环境0:

java  scala nc.exe

首先需要开启端口监听

D:\> nc -L -p 9999 -v
正在监听[任何一个(多个)] 9999 ...
连接到 [192.168.0.100] 来自 PC-20161208TLXD [192.168.0.100] 5681
113,edf
112,3fr
12f,ghj
46t,fhgd
qwe,fg

然后启动代码

猜你喜欢

转载自blog.csdn.net/qq_29493353/article/details/84973271
今日推荐