Spark Streaming的window操作实战模拟新浪微博、百度、京东等热点搜索词案例实战

1.代码:

 

    val conf = new SparkConf();

    conf.setAppName("OnlineHottestItems");

    conf.setMaster("spark://Master:7077");

 

    /**

      * 此处设置Batch Interval是在Spark Streaming中生成基本job的时间单位,窗口和滑动时间间隔

      * 一定是改Batch Interval的整数倍

      */

    val ssc = new StreamingContext(conf, Seconds(5));

 

    ssc.checkpoint("/library/onlinehot/")

 

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

 

    /**

      * 用户搜索的格式简化为name item,在这里我们由于要计算出热点内容,所以只需要提取item即可

      * 提取出的item然后通过map转换为(item,1)

      */

    val searchPair = hottestStream.map(_.split(" ")(1)).map(item => (item, 1))

    //val hottestDStream = searchPair.reduceByKeyAndWindow((v1: Int, v2: Int) => v1 + v2, Seconds(60), Seconds(20))

 

    val hottestDStream = searchPair.reduceByKeyAndWindow((v1: Int, v2: Int) => v1 + v2, (v1: Int, v2: Int) => v1 - v2, Seconds(60), Seconds(20))

    //如果操作没有排序,可以通过transform扩展

    hottestDStream.transform(hottestItemRDD => {

      val top3 = hottestItemRDD.map(pair => (pair._2, pair._1)).sortByKey(false).

        map(pair => (pair._2, pair._1)).

        take(3) //选出前3个

      for (item <- top3) {

        println(item)

      }

 

      hottestItemRDD

    }).print

 

    /**

      * 计算后的有效数据一般都会写入kafka中,下游的计费系统会从kafka中pull到有效数据进行计费

      */

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值